<?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 Natthanan Bhukan on Medium]]></title>
        <description><![CDATA[Stories by Natthanan Bhukan on Medium]]></description>
        <link>https://medium.com/@RTae?source=rss-57a2f5f364a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mDEPYHKz3RxxmdaqEKJvbw.jpeg</url>
            <title>Stories by Natthanan Bhukan on Medium</title>
            <link>https://medium.com/@RTae?source=rss-57a2f5f364a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 18:01:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@RTae/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[Review for the Certified Kubernetes Application Developer (CKAD) Exam: Key Areas and Strategies]]></title>
            <link>https://medium.com/@RTae/review-for-the-certified-kubernetes-application-developer-ckad-exam-key-areas-and-strategies-875ee5aa6c27?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/875ee5aa6c27</guid>
            <category><![CDATA[ckad]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ckad-exam]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 07:43:50 GMT</pubDate>
            <atom:updated>2025-02-10T07:43:50.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rro_Qhrcj4kyCQnb" /></figure><p>Hello everyone, my name is Tae. Several months ago, I took the <a href="https://training.linuxfoundation.org/certification/certified-kubernetes-application-developer-ckad/"><strong>Certified Kubernetes Application Developer, or CKAD,</strong></a><strong> </strong>exam,<strong> </strong>and<strong> </strong>I feel it is a good idea to share my opinion and my insights in this exam. Therefore, this article will provide what CKAD is, its criteria, how to prepare, and tips.</p><h3>Table of contents</h3><ul><li>What is CKAD and its focus area?</li><li>How to prepare for an exam</li><li>Exam tips</li></ul><h3>What is CKAD and its focus area?</h3><p><strong>The Cloud Native Computing Foundation (CNCF)</strong> offers the <strong>CKAD</strong> certificate to validate a developer’s ability to build, deploy, and troubleshoot apps in Kubernetes. It covers core concepts like pod design and config management. Also, it covers observability, networking, state persistence, and security best practices. This certificate certifies that people have the skills to build and manage production apps in Kubernetes.</p><blockquote>The successful candidate will be comfortable:<br>– working with (OCI-compliant) container images<br>– applying Cloud Native application concepts and architectures<br>– working with and validating Kubernetes resource definitions</blockquote><p>These texts above are from the CKAD certificate’s website. It shows test takers must know about containers and cloud-native apps and how to implement them into the system using Kubernetes. This may imply that you may need experience in developing apps and designing software architectures. However, in my opinion, this exam does not require deep knowledge of cloud computing or using advanced Kubernetes skills. It will test your software design skills and your ability to implement it with basic Kubernetes skills.</p><p><strong>Exam Curriculum</strong></p><p>As I mentioned, CKAD focuses on developing software with Kubernetes. Therefore, if you have skills in software architecture design, you have an advantage in this. This is because most of the questions are about how to use or configure a service for each use case. Also, you can see the list of the exam curriculum below to understand its criteria.</p><p><em>Application Design and Build (20%)</em></p><ul><li>Define, build, and modify container images.</li><li>Choose and use the right workload resource (Development, DaemonSet, CronJob, etc.).</li><li>Understand multi-container pod design patterns (e.g., sidecar, init, and others).</li><li>Utilise persistent and ephemeral volumes.</li></ul><p><em>Application Deployment (20%)</em></p><ul><li>Use Kubernetes primitives to implement common deployment strategies (e.g., blue/green or canary).</li><li>Understand deployments and how to perform rolling updates.</li><li>Use the Helm package manager to deploy existing packages.</li><li>Kustomize.</li></ul><p><em>Application Observability and Maintenance (15%)</em></p><ul><li>Understand API deprecations.</li><li>Implement probes and health checks.</li><li>Use built-in CLI tools to monitor Kubernetes applications.</li><li>Utilise container logs.</li><li>Debugging in Kubernetes.</li></ul><p><em>Configuration and Security (25%)</em></p><ul><li>Discover and use resources that extend Kubernetes (CRD, operators).</li><li>Understand authentication, authorisation, and admission control.</li><li>Understand requests, limits, and quotas.</li><li>Define resource requirements.</li><li>Understand ConfigMaps.</li><li>Create and consume secrets.</li><li>Understand ServiceAccounts.</li><li>Understand application (security contexts, capabilities, etc.).</li></ul><p><em>Services &amp; Networking (20%)</em></p><ul><li>Demonstrate a basic understanding of network policies.</li><li>Provide and troubleshoot access to applications via services.</li><li>Use Ingress rules to expose applications.</li></ul><h3>How to prepare for an exam</h3><p>There are plenty of courses or books that teach about how to use Kubernetes and the concept of Kubernetes. Likewise, I have my own list of the material to prepare for the exam. Although I do not claim this list is the best material to prepare for the CKAD exam since everyone has their own preferences. Thus, I hope my list could be useful as a guideline for you.</p><p><strong>Book</strong></p><ul><li><a href="https://www.oreilly.com/library/view/kubernetes-in-action/9781617293726/?_gl=1*qmidw5*_ga*MjAyMTAxMDAwMi4xNzM3NjEzMTg2*_ga_092EL089CH*MTczNzYxMzE4NS4xLjEuMTczNzYxMzQzMS41OS4wLjA."><strong>Kubernetes in Action:</strong></a><strong> </strong>This one provides a core concept and how to implement Kubernetes into the system. I would recommend this book to those who are starting to learn Kubernetes. It’s a good starting point for me.</li><li><a href="https://www.oreilly.com/library/view/certified-kubernetes-application/9781098152857/?_gl=1*g84tx6*_ga*MjAyMTAxMDAwMi4xNzM3NjEzMTg2*_ga_092EL089CH*MTczNzYxMzE4NS4xLjEuMTczNzYxMzUxMy42MC4wLjA."><strong>Certified Kubernetes Application Developer (CKAD) Study Guide, 2nd Edition</strong></a><strong>: </strong>This book offers good guidance on how to prepare for the exam, but you can skip it, if you take an online course.</li></ul><p><strong>Videos</strong></p><ul><li><a href="https://www.youtube.com/watch?v=X48VuDVv0do"><strong>Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours] By Nana</strong></a>: I watched this video when I was starting to learn Kubernetes. It is a good video for learning Kubernetes.</li><li><a href="https://www.youtube.com/watch?v=2T86xAtR6Fo"><strong>Complete Kubernetes Course — From BEGINNER to PRO By DevOps Directive</strong></a><strong>: </strong>While preparing for this exam, this video provides a good concept in Kubernetes. For people who are looking for a video to recap knowledge before taking an exam, I would suggest this.</li></ul><p><strong>Courses</strong></p><ul><li><a href="https://www.udemy.com/course/learn-kubernetes/?srsltid=AfmBOorDsZnyJAjDLB4u9rUackM6pYyb29SOQAwstwgtZHyNYIooLg3Y&amp;couponCode=ST16MT28125AROW"><strong>Kubernetes for the Absolute Beginners—Hands-on:</strong></a><strong> </strong>I also took this course when I was studying two years ago. They also have a platform for learning and playing with Kubernetes. It is great for testing concepts learnt on <a href="https://kodekloud.com/">Kodekloud</a>.</li></ul><p><strong>Practice and Mock exam</strong></p><ul><li><a href="https://killer.sh/"><strong>Killer.sh</strong></a><strong>: </strong>When you buy an exam from the Linux Foundation. They will provide a mock exam for the test taker. You should try it one time because this helps you become familiar with the exam and the interface used during the exam.</li><li><a href="https://kodekloud.com/"><strong>Kodekloud</strong></a><strong>: </strong>I recommend this one. Their practices and exams are good for both practice and use in real life.</li></ul><p>For my preference, I usually do hands-on practice or try a mock exam. For the hands-on practice, I did a mini project to test my understanding and get familiar with the Kubernetes commands. Likewise, I practice with an old exam from GitHub or practice on <a href="http://killer.sh/"><strong>Killer.sh</strong></a><strong>.</strong></p><h3>Exam tips</h3><p><strong>Prepare environment before taking a test</strong></p><p>You can add a shortcut command in your exam environment for quick access to your commands. I have several recommended shortcuts that show in the list below.</p><ol><li><strong>alias k=”kubectl”: </strong>Shortest kubectl command</li><li><strong>alias ka=”kubectl apply -f”:</strong> Apply Kubernetes resource from file</li><li><strong>alias kc=”kubectl create -f”:</strong> Create Kubernetes resource command with imperative command</li><li><strong>export dr=” — dry-run=client -o yaml”:</strong> Dry run the argument and show a YAML file before applying. This setup is very useful for debugging Kubernetes commands. You can use it as an environment variable along with a Kubectl command like this: <strong>kubectl create deployment my-dep — image=busybox $dr</strong></li><li><strong>export gf=” — grace-period 0 -force”: </strong>Force delete pod and run a command by <strong>kubectl delete pod baz $gf.</strong> It will delete a pod immediately.</li></ol><p><strong>Try to use Imperative Commands rather than copying from YAML from document</strong></p><p>The main reason that I suggest using this method is that it is quicker. There are several commands that you should keep using while practicing Kubernetes. It lets you access commands quicker and reduces YAML syntax errors. There are serveral commands that I recommend remembering.</p><ol><li>kubectl run: For creating a new pod with specific settings.</li><li>kubectl create: For creating a resource with the specified configuration.</li><li>kubectl expose: Exposing a port on a running pod, deployment and statefull.</li></ol><p>Also, try to remember the short names of the reasons. It’s not hard to remember since the short name goes along with the full name.</p><ul><li>pods -&gt; po</li><li>jobs -&gt; jobs</li><li>cronjobs -&gt; cj</li><li>deployment -&gt; deploy</li><li>configMaps -&gt; cm</li><li>secrets -&gt; secrets</li><li>serviceaccounts -&gt; sa</li><li>services -&gt; svc</li><li>namespaces -&gt; ns</li><li>replicasets -&gt; rs</li><li>networkpolicies -&gt; netpol</li><li>persistentVolumes -&gt; pv</li><li>persistentVolumeClaims -&gt; pvc</li></ul><p>For example, if you would like to create a deployment with an Nginx image and three replicas, you can run a command that looks like this.</p><pre>kubectl create deploy test --image=nginx -r 3 --dry-run=client -o yaml<br><br># For Shorter command, you can see the number of character decrease significant by using env, alian and shortname<br>kc deploy test --image=nginx -r 3 $dr</pre><p><strong>Get familiar with the Kubernetes document</strong></p><p>Yeah, that sounds boring, but you need to do it. This is because in the exam you cannot use Google to search for your error or how to provision resources. Therefore, you need to know how to use the <a href="https://kubernetes.io/docs/home/"><strong>Kubernetes documentation,</strong></a><strong> </strong>which<strong> </strong>is the only webpage that you can use while taking an exam.</p><h3>Summary</h3><p>The exam is not very tough for me. It tests your basic Kubernetes skills and your ability to use it in a project. If you have 1-2 years of experience in Kubernetes, you can pass this exam with 1-2 months of preparation. Thus, I would suggest trying to deal with real-life problems and mock exams that will make you successful in the exam for sure.</p><blockquote>Also, passing this exam will not guarantee you are a master of Kubernetes, so keep learning. After I took this exam, I found many concepts in Kubernetes that I still need to learn 🤣.</blockquote><blockquote>Good luck on the exam 🚀</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvd_0J7XnuDBMKbUBbnXDw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875ee5aa6c27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhanced LLM Applications with Monitoring and Observability]]></title>
            <link>https://medium.com/cj-express-tech-tildi/enhanced-llm-applications-with-monitoring-and-observability-70aac39cb1c4?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/70aac39cb1c4</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning-engineer]]></category>
            <category><![CDATA[langfuse]]></category>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 10:20:25 GMT</pubDate>
            <atom:updated>2024-09-25T10:20:25.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrkGE37ltczeSI8qMnmgUA.png" /></figure><p>Hi, my name is Tae, and I’m a Machine Learning Engineer (MLE) from <strong>CJ Express Tech (TILDI)</strong>. In this article, I would like to share information about monitoring and observability in LLM applications for those who are working on LLM projects and looking for a solution to monitor their systems. Monitoring and observability are crucial components for software architects to monitor and understand a system’s behaviour, since infrastructure engineers use these tools in their systems to monitor and alert before a catastrophic event occurs or analyse the data to enhance the system in the future.Therefore, I would like to share <a href="https://langfuse.com/"><strong>Langfuse,</strong></a><strong> </strong>which is a tool for developing monitoring and observability in LLM applications.</p><h4>Table of Contents</h4><ul><li>Monitoring and Observability in ML Application</li><li>How to do it in LLM Application</li><li>Langfuse Features</li></ul><h4>Monitoring and Observability in ML Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sN1MajqIIOwSh6qw5gROfg.png" /></figure><p>Monitoring and observability are not new topics since software architecture always puts it into their system design to ensure systems get monitored and observed. Therefore, we should understand the meaning of monitoring and observability, and these are my short versions.</p><p><strong>Monitoring: </strong>tools or processes to trace and collect a metric or log. Then, using this data to create an alert system and visualisation.</p><p><strong>Observability: </strong>a process to deeply understand metrics, log, and trace to analyse system behaviour and then use these data to improve the system later.</p><p>The main difference between <strong>monitoring </strong>and<strong> observability </strong>is that<strong> </strong>monitoring is a tool or process to collect data, while observability focuses on using these data to analyse a system and improve the system. As a result, monitoring<strong> </strong>and<strong> </strong>observability<strong> </strong>play a<strong> </strong>crucial role in providing insightful data to help developers understand and improve their systems.</p><p><strong>How to Implement Monitoring and Observability in ML Applications</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jQggI16UrZ6plijxCeNWQ.png" /><figcaption>Figure 1 Engineers can implement a monitoring and observability system for this type of ML input.</figcaption></figure><p>Basically, we can observe raw input data to see a change in each input in the data source, but in the real world, it is usually hard to monitor and can cause a frequency of errors from humans, so engineers will create a validation logic to validate input data before feeding it into the system.</p><p>As a result, most ML engineers try to implement monitoring and observability in the feature, predictions, and accuracy data.</p><ol><li><strong>Features Data: </strong>Features are well structured following a predefined schema, so we can do feature validation to ensure that your features follow an expected schema.</li><li><strong>Prediction Data: </strong>Distribution shifts are a common method for observing this type of data. This is because the weights and biases of the AI model do not change, so a slight difference in the prediction distribution generally indicates a difference in the underlying input distribution, such as predicting an unusual number of false in a row.</li><li><strong>Accuracy: </strong>By using a predefined metric from the model to compute accuracy in case you have ground truth data or using feedback from the user to receive feedback accuracy from the user. For instance, an image classification system that allows users to provide feedback on a prediction result. As a result, the system can use this data to compute accuracy from the model’s metrics, such as F1, recall and precision.</li></ol><h4><strong>How to do it in LLM Application</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7ouxLcHsRrgEMPp_jFWoQ.png" /></figure><p>Moreover, ML observability knowledge can be extended to the LLM observability system by implementing the following set of metrics.</p><ol><li><strong>Cost</strong>: Monitoring tokens per request or tokens per model to keep track of usage in each model and then converting tokens per request into a budget to optimise the service and reduce cost.</li><li><strong>Latency</strong>: The request latency in each LLM application is to ensure the performance of the system and do a root cause analysis when performance is not as expected.</li><li><strong>Tracing data</strong>: In LLM applications, there are many functions and data,. For instance, the internal state of the application along with the input and output of the application can be useful when <strong>AI researchers</strong> need to analyse the effect of input on each input.</li><li><strong>Feedback from users</strong>: Currently, most LLM applications are based on text messages, so engineers or researchers can use this feedback to improve model performance.</li><li><strong>Model metric</strong>: Like another ML model, engineers can use LLM’s metric to create a report of model performance by using input from the user with the model’s metric.</li></ol><p>Therefore, by implementing observability techniques to gain a deep understanding of the metrics from monitoring, we can obtain these benefits in order to improve a system.</p><ol><li><strong>Better Performance</strong>: These data allowed engineers or researchers to understand the issues or bottlenecks of the system, so they established a way to improve performance.</li><li><strong>Better explainability</strong>:<strong> </strong>Tracing each input and output in each LLM application component allowed research to deep-analyze the model behaviour along with each model prompt to improve it.</li><li><strong>Cost optimisation: </strong>For better visibility, track the cost per request in each model. Engineers can use this data to improve services that consume excessive amounts of resources.</li></ol><h4>Langfuse Features</h4><blockquote>The review features are not part of the pro and team packages, so there are some features that are missing in this article, such as web base evaluation, playground and third-party integration.</blockquote><p><strong>Tracing</strong></p><p>This is the main feature of Langfuse. It allows developer to trace the state of input or output in each component by using simple integration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SS57olfT8jHPh4cZ59_Xyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*vrexVLKY9TupgBOm5E5tKw.png" /><figcaption>Figure 2 Tracing feature allowed user to trace a state in the system</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyvqnOV73emgBMeKjHLmsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JrkrJtqxVhwNfbb5TH95Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EX-BuzvAF02032212MI6vg.png" /><figcaption>Figure 3 Inside trace data shows the input and output in each component</figcaption></figure><p>As shown in figures 2 and 3, when sending data into the chat API, developers can use a Langfuse SDK to monitor each message and trace this data in the function. Then, Langfuse will store data in a proper format which will help AI researchers understand their models or their prompt behaviour. Also, Langfuse provides a timeline chart to see the latency and order of the executed component, and in each component, developers can look into the input and output of the module for further analysis.</p><p>For integration, developer can pass a call-back function into the LLM framework or use a decorator at the top of the function to let Langfuse SDK capture the state data. Since there are numerous methods to integrate with Langfuse, including Flowise, OpenAI, and LlamaIndex, I strongly advise reading this <a href="https://langfuse.com/docs/integrations/overview">document</a>. I have included my code below if you are using Langchain.</p><pre># Initialize chat histories dictionary<br>chat_histories = {}<br>@observe()<br>def conversation(user_id: str, session_id:str, question: str):<br>    # Ensure the user has a chat history<br>    if user_id not in chat_histories:<br>        chat_histories[user_id] = []<br><br>    # Get the user&#39;s chat history<br>    user_chat_history = chat_histories[user_id]<br><br>    # Add the new question to the user&#39;s chat history<br>    user_chat_history.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: question})<br><br>    _, _, risk_score = toxicity_scanner.scan(question)<br><br>    langfuse_context.score_current_observation(<br>        name=&quot;input-toxicity&quot;,<br>        value=risk_score<br>    )<br>    langfuse_handler = langfuse_context.get_current_langchain_handler()<br>    trace_id = langfuse_handler.get_trace_id()<br><br>    answer = general_chain.invoke(<br>        {<br>            &quot;question&quot;: question, <br>            &quot;chat_history&quot;: user_chat_history<br>        },<br>        config={&quot;callbacks&quot;: [langfuse_handler]}<br>    )<br><br>    if answer.lower() == &quot;llm agent&quot;:<br>        answer = llm_agent_chain.invoke(<br>            question,<br>            config={&quot;callbacks&quot;: [langfuse_handler]}<br>        )<br>    langfuse_context.update_current_observation(<br>        input=question,<br>        output=answer,<br>        session_id=session_id,<br>        user_id=user_id,<br>        tags=langfuse_prompt.config[&quot;tags&quot;]<br>    )<br>    # Add the assistant&#39;s response to the user&#39;s chat history<br>    user_chat_history.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: answer})<br>    <br>    langfuse_handler.flush()<br>    <br>    return answer, trace_id</pre><p>Another point is that developers can query data later using sessions or user formats because Langfuse allows developers to pass both a user_id and a session_id as meta data. This will be helpful if researchers want to examine the user chat history or messages from the entire session.</p><pre>    langfuse_context.update_current_observation(<br>        input=question,<br>        output=answer,<br>        session_id=session_id,<br>        user_id=user_id,<br>        tags=langfuse_prompt.config[&quot;tags&quot;]<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yF7dnle5vPqzfj0StXQ2Aw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0muuSgUUaeGR6YBgjGyAg.png" /><figcaption>Figure 4 Langfuse uses session IDs to group trace data into one group of trace data.</figcaption></figure><p>Figure 4 illustrates how Langfuse formats data into groups of trace using the session IDs added to the trace function. The session IDs are then stored in the trace data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wi5iytWyJ6dS_kheqRyWnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40HRDskGBWR0BKpqyqL0TA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGngPAhLon0lwLaypXjEyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zlJalSE_RAayvTm9ZJD3g.png" /><figcaption>Figure 5 The user page will summarise trace data by using the user ID.</figcaption></figure><p>Likewise, the user page uses the user ID to summarise the data, as you can see in Figure 5. This page shows trace data in session and trace format for each user, so researchers can explore the data for each user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4zRewdssNYDsoFBzNh2QQ.png" /><figcaption>Figure 6 The generation page shows data from the LLM API.</figcaption></figure><p>Additionally, Langfuse offers another page called Generation that displays only results from an LLM API. This page gives developers access to usage, input, and output data from the LLM API, enabling them to continuously track message latency or usage data. In the next section, I will demonstrate how developers can maintain the trace prompt with a message from the client by passing a prompt version into the trace data.</p><p><strong>Scores</strong></p><p>To create an observation system, we need some sort of indicator. Therefore, Langfuse offers a feature called &quot;score&quot; that enables developers to compute a custom metric score and store it in a score record that is linked to trace data. To gain a deep understanding of their model&#39;s behaviour, developers or researchers can thus examine the scores in each data trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwR5_40UKMLVcM57mecOyA.png" /><figcaption>Figure 7 With the help of the score feature, developers can create a unique score for every data trace.</figcaption></figure><p>For example, my API computes a score as soon as it receives a request and uses input toxicity to check the input toxic score.</p><pre>    langfuse_context.score_current_observation(<br>        name=&quot;input-toxicity&quot;,<br>        value=risk_score<br>    )</pre><p>Developers can also put in place a system for calculating metrics at a later time. This is because computing the score for each request cannot be done in parallel and could negatively impact system performance. If a system to schedule queries on Langfuse&#39;s trace data is put in place, developers can generate a daily report to monitor a model every day. The data should then be kept in Langfuse so that the developer can query it later to create a report.</p><pre>from langfuse import Langfuse<br>from config import settings<br>from uptrain import EvalLLM, Evals<br>import os<br> <br>os.environ[&quot;LANGFUSE_PUBLIC_KEY&quot;] = settings.LANGFUSE_PK_KEY<br>os.environ[&quot;LANGFUSE_SECRET_KEY&quot;] = settings.LANGFUSE_SK_KEY<br>os.environ[&quot;LANGFUSE_HOST&quot;] = settings.LANGFUSE_HOST<br> <br>langfuse = Langfuse()<br> <br>langfuse.auth_check()<br><br>def get_traces(service_name,limit=10000):<br>    all_data = []<br>    page = 1<br> <br>    while True:<br>        response = langfuse.client.trace.list(<br>            tags=[f&#39;service_name:{service_name}&#39;],<br>            page=page,<br>            order_by=None<br>        )<br>        if not response.data:<br>            break<br>        page += 1<br>        all_data.extend(response.data)<br>        if len(all_data) &gt; limit:<br>            break<br> <br>    return all_data[:limit]<br><br>def main():<br>    traces_sample = get_traces(&quot;sale&quot;)<br>    evaluation_batch = []<br>    for t in traces_sample:<br>        observations = [langfuse.client.observations.get(o) for o in t.observations]<br>        for o in observations:<br>            if (o.name == &quot;VectorStoreRetriever&quot;):<br>                evaluation_batch.append({<br>                    &quot;trace_id&quot;: t.id,<br>                    &quot;context&quot;: o.output,<br>                    &quot;question&quot;: t.input,<br>                    &quot;response&quot;: t.output<br>                })<br>    <br>    eval_llm = EvalLLM(openai_api_key=settings.OPENAI_KEY)<br>    results = eval_llm.evaluate(<br>        data=evaluation_batch,<br>        checks=[Evals.CONTEXT_RELEVANCE, Evals.FACTUAL_ACCURACY, Evals.RESPONSE_COMPLETENESS]<br>    )<br><br>    for row in results:<br>        for metric_name in [&quot;context_relevance&quot;, &quot;factual_accuracy&quot;,&quot;response_completeness&quot;]:<br>            langfuse.score(<br>                name=metric_name,<br>                value=row[&quot;score_&quot;+metric_name],<br>                trace_id=row[&quot;trace_id&quot;]<br>            )<br><br><br>if __name__==&quot;__main__&quot;: <br>    main()</pre><p><strong>Prompt</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4FIh7pZhpnvaIuRVdn7lA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgV95Ca9h_uFUEAkoMgHGg.png" /><figcaption>The features shown in Figure 8 Prompts enable developers to control the configuration of their models and provide version management prompts.</figcaption></figure><p>Additionally, Langfuse offers a feature that lets users control the configuration of an LLM model or prompt. Consequently, during the model&#39;s deployment, the developer has the ability to advance or retract the prompt and LLM model configuration. As you can see in Figure 8 (right), this feature also enabled users to manage their configuration with version. I can promote or rollback using any of my eight configuration versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPsau5cuXVkHghwYs_FLug.png" /><figcaption>Figure 9 Tracing integration with prompt</figcaption></figure><p>Developers can also associate their prompt with a particular version and name with Generation, which enables them to monitor the effectiveness of their prompt for assessment at a later time. Though we hope to utilise this feature in the future with Langchain or Llamaindex, Langfuse does not support these for this feature.</p><p><strong>Additional feature</strong></p><p>1.Models</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFFbOnWhLI2Ulc6bFZBicQ.png" /><figcaption>Figure 10: The model configuration enables Langfuse to track generation data and determine the associated costs.</figcaption></figure><p>Each LLM API has a different price depending on the service provider. Thus, using a RegEx format to specify their own usage in each model, Langfuse gives developers the ability to obtain the tokeniser name and then compute the cost.</p><p>2. Dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBjdfo4JWhBKI8RR6yHahw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRkzB8wMHvVyYd396nuzQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jaT6D_CH03rAjyPZaAU2A.png" /><figcaption>Figure 11: Dataset management for later model evaluation using these data</figcaption></figure><p>Allowing developers to assess a model&#39;s performance prior to deploying it into production is the primary objective of this feature. Before deploying, the dataset feature offers a master dataset with a run experiment to verify the model&#39;s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnDYL4aNV7ooNmeDMZ3E4w.png" /><figcaption>Figure 12: Design of the dataset work flow</figcaption></figure><p>Figure 12 illustrates how the Langfuse Dataset functions as a master dataset, allowing developers to assess their models prior to deployment. They can also manually generate datasets using either synthetic or real user data.</p><p>3. Export Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qg6ZqS_02SB1AY4RaQmWIg.png" /><figcaption>Figure 13: Using Langfuse UI to export data</figcaption></figure><p>Researchers can use the UI, Langfuse SDK, and API to export data from Generation and use it to fine-tune a model. Users can manipulate the data into the format of their choice because it is linked to scores and trace values.</p><p>4. Project and user management</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7ny0bBZQq_4WKlLsldHBw.png" /><figcaption>Figure 14: Page of project management</figcaption></figure><p>In order to give Platform Engineers fine-grained access to each user, Langfuse offers a section dedicated to managing user and SSO authentication (documents) for project and user management.</p><p><strong>Code</strong></p><p><a href="https://github.com/RTae/demo-langfuse">GitHub - RTae/demo-langfuse</a></p><h4>Summary</h4><p>In conclusion, developers (software engineers or AI researchers) may be able to better understand their systems through the use of an observability and monitoring system. In this post, I aim to clarify Langfuse and highlight the advantages of incorporating observability and monitoring into software systems. Hopefully, this will help readers better understand Langfuse and its applications. Lastly, you can explore Langfuse and integrate it on your own using internal tools like Prometheus, PostHog, Backstage, etc. as my demonstration is a part of several features in Langfuse.</p><h4>Reference</h4><ul><li><a href="https://encord.com/blog/ml-monitoring-vs-ml-observability">ML Monitoring vs. ML Observability</a></li><li><a href="https://langfuse.com/docs">Open Source AI Engineering Platform - Langfuse</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5r-WMlRXtjI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5r-WMlRXtjI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5r-WMlRXtjI%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/8e3a3beb399435db99925e7bdfb8021c/href">https://medium.com/media/8e3a3beb399435db99925e7bdfb8021c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70aac39cb1c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cj-express-tech-tildi/enhanced-llm-applications-with-monitoring-and-observability-70aac39cb1c4">Enhanced LLM Applications with Monitoring and Observability</a> was originally published in <a href="https://medium.com/cj-express-tech-tildi">CJ Express Tech (TILDI)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does vLLM optimize the LLM serving system?]]></title>
            <link>https://medium.com/cj-express-tech-tildi/how-does-vllm-optimize-the-llm-serving-system-d3713009fb73?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3713009fb73</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vllm]]></category>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 06:14:51 GMT</pubDate>
            <atom:updated>2024-07-13T04:36:35.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43CI3e9CJ17JcPzFM2z0GA.png" /></figure><p>Hi, my name is Tae, and I’m a Machine Learning Engineer (MLE) from <strong>CJ Express Tech (TILDI)</strong>. In this article, I would like to share ideas for serving LLM. Due to the fact that serving LLM doesn’t similarly deploy another type of machine learning, I will share its challenge, their technique, and demonstrate how to solve this issue via <a href="https://github.com/vllm-project/vllm">vLLM</a>.</p><h3>Table of content</h3><ul><li>Why is serving LLM so challenging?</li><li>What is vLLM?</li><li>What is vLLM’s secret sauce?</li><li>Demo</li></ul><h3>Why is serving LLM so challenging?</h3><h4>Computational Resources</h4><p>Due to the fact that LLM has numerous parameters to perform a prediction, which could start with the 7B parameter and then go up to 321B, deploying this model may require an intensive resource and a lot of optimization rather than using a traditional method to deploy a machine learning model.</p><h4>Latency</h4><p>When a sentence or token is complicated, the process takes several minutes to compute a result for the client, which may cause an issue on a large scale or in real-world business. For instance, a company may apply LLM with a product Q&amp;A chatbot, which has a slow response to each question, which could cause frustration for the user. Therefore, applying some method to reduce the latency would be a good practice.</p><h4>Cost</h4><p>In a large-scale system or with multiple LLMs in the system, which would consume a lot of budget for the application since LLMs use large resources to process, as a MLE, finding a way to utilize a resource would bring a financial benefit to the system. For instance, lower the cost per request.</p><h3>What is vLLM?</h3><p>This project is from UC Berkeley’s students, who have a passion to optimize serving performance in LLMs. Many systems spend a lot of resources on serving LLMs. However, it has a poor response time when using a simple method to deploy it. As a result, vLLM’s team proposes a new method to solve this issue by using the <strong>OS’s virtual memory</strong> design, which could improve <strong>LLM serving performance </strong>around <strong>24 times </strong>while using<strong> half the memory of the GPU compared with the traditional method. </strong>To integrate into your system<strong>, vLLM </strong>provides a simple interface that lets machine learning engineers (MLE) develop it via a Python interface, which you could integrate into your system without using fancy packages or dependencies.</p><h3>What is vLLM’s secret sauce?</h3><p>To understand how vLLM achieves the goal of reducing latency and optimizing overall performance in the system, we should know the bottleneck for vLLM and how to resolve this issue.</p><h4>Memory Usage Issue</h4><p>Basically, a large language model, or LLM, is a branch of attention neural network, or what some people will refer to as a transformer, with custom decoding based on the model. So, we need to understand a key concept: how LLM generates a token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*qyCUwOx03NtgSD3C.png" /><figcaption>Fig. 1: Attention formula</figcaption></figure><p>In the autoregressive process of the model, it will compute an attention formula to select a key word as an output. The formula consists of three variables.</p><p><strong>Query (Q):</strong> A new token in the decoder step or the last token that the model has seen</p><p><strong>Key (K):</strong> Previous context that the model should attend</p><p><strong>Value (V):</strong> Weighted sum over previous context</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaKM3BEA8Gq--iEjewjiuQ.png" /><figcaption>Fig. 2: How QKV is computing in the Attention model</figcaption></figure><p>In the mean time, <strong>Query </strong>is a vector of the dot product between word embedding and weight. <strong>Key</strong> and <strong>Value</strong> are matrices since they need to store the previous context and the weight sum of the previous context, which is referred to as the <strong>KV cache</strong>.</p><p>The main reason that model needs to store <strong>Key</strong> and <strong>Value</strong> is that<strong> </strong>it’s an attention algorithm that needs to process a <strong>Query </strong>variable of previous <strong>Key</strong> and <strong>Value </strong>before generating a new token, which could be a massive compute cost. If it doesn’t store, the model could cache it due to the fact that in an auto-regressive process, the compute of the previous context doesn’t change.</p><p>So, how does it affect the model’s performance? It reduces the number of requests and key generation length since long texts require a huge KV cache to store. According to <strong>Efficient Memory Management for Large Language Model Serving with PagedAttention,</strong> around 30 percent of GPU memory is occupied by <strong>KV cache</strong>. Moreover, this statement could lead to another issue about memory usage.</p><p>To get more ideas about how attention is working or how KV cache is managed, I recommend watching these videos.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPSs6nxngL6k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPSs6nxngL6k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPSs6nxngL6k%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bafd58c50fc53a0c59ce8c955934eee/href">https://medium.com/media/2bafd58c50fc53a0c59ce8c955934eee/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F80bIUggRJf4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D80bIUggRJf4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F80bIUggRJf4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef1832cac9ed21ab9c3bcd7b655d90af/href">https://medium.com/media/ef1832cac9ed21ab9c3bcd7b655d90af/href</a></iframe><h4>Memory Fragmentation</h4><p>Basically, the KV cache of a request is stored in contiguous memory space, since many deep learning frameworks compute with tensor values that need to be stored in contiguous memory. However, KV caches could shrink and grow over time, depending on the model architecture. This storage format could cause an issue and is not useful for computing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*U4TiteNDyfFDEFf4.png" /><figcaption>Fig. 3. <strong>Internal</strong> <strong>Fragmentation </strong>(<a href="https://www.geeksforgeeks.org/difference-between-internal-and-external-fragmentation/">https://www.geeksforgeeks.org/difference-between-internal-and-external-fragmentation/</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*W9uRB686Fyr8v8s9.png" /><figcaption>Fig. 4. <strong>External</strong> <strong>Fragmentation </strong>(<a href="https://www.geeksforgeeks.org/difference-between-internal-and-external-fragmentation/">https://www.geeksforgeeks.org/difference-between-internal-and-external-fragmentation/</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*BHJ8hWRCufQrZ4q43_ftSA.png" /><figcaption>Fig. 5. KV cache memory management in existing systems (<strong>PageAttention</strong> paper)</figcaption></figure><p><strong>Memory fragmentation </strong>isn’t a new issue. We could experience this problem in OS memory management. This issue relates to how OS allocates memory, which could be separated into two kinds.</p><ol><li><strong>Internal</strong> <strong>Fragmentation</strong>:<strong> </strong>For instance, Process A requests 32 MB of memory, but it uses only 28 MB, leaving 4 MB that another process couldn’t use since it was reserved by Process A.</li><li><strong>External Fragmentation </strong>When many processes request blocks of memory with a variety of sizes, it could cause a hole in the memory, which is like a gap in memory.</li></ol><p>In terms of the NLP problem, let’s compare the process as a request, and the KV cache is a byte that needs to be stored in the GPU, as you could see from Fig. 5, which shows internal and external fragmentation in the memory.</p><p>Overall, <strong>memory fragmentation </strong>would cause underutilization of the system due to the fact that it couldn’t use a fragment of memory in the system. As a result, the system will not be able to handle large models or large requests.</p><h4>How to overcome this issue</h4><p>The<strong> vLLM</strong> team has developed a new attention algorithm called <strong>PageAttention</strong>, which is inspired by the OS’s<strong> virtual memory</strong> concept. One could think of blocks as pages, tokens as bytes, and requests as processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*03Hf5kq1FyxR3GKT.gif" /><figcaption>Fig. 6. Generation process for a request with PagedAttention. (<a href="https://blog.vllm.ai/2023/06/20/vllm.html">https://blog.vllm.ai/2023/06/20/vllm.html</a>)</figcaption></figure><p>By using a logical KV cache block <strong>(virtual memory)</strong> for storing each token (<strong>byte) </strong>from the prompt<strong> </strong>and mapping the <strong>block table (page table) </strong>into a physical KV cache block (<strong>physical memory),</strong>. Consequently, physical GPU memory will be allocated when the system needs it. In theory, it will eliminate <strong>internal fragmentation and external fragmentation</strong> since the token stores the same cache block size and allocates it when the system requests it, which means no more pre-allocation.</p><h4><strong>Another benefit of using PageAttention</strong></h4><p>Using <strong>PageAttention </strong>allowed the system to share a KV cache since it stores tokens in non-contiguous memory. Which led to many applications for a LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GBmPfsRIEl3BuCBt.gif" /><figcaption>Fig. 7. Generation process for a request that samples multiple tokens. ((<a href="https://blog.vllm.ai/2023/06/20/vllm.html">https://blog.vllm.ai/2023/06/20/vllm.html</a>))</figcaption></figure><ol><li><strong>Copy-on-Write Mechanism: </strong>Of course, using the same feature as the OS’s virtual memory, <strong>PageAttention </strong>could implement this mechanism<strong> </strong>by referencing the same request logical KV cache block into the same physical KV cache block. <strong>Fig. 7 </strong>illustrates<strong> </strong>an<strong> </strong>idea<strong> of</strong> how it works.</li><li><strong>Beam search</strong>: In NLP tasks, beam search is a common use case to select a suitable output token. In the traditional method, the beam search needs to generate all possible tokens for each beam candidate without sharing the KV cache. Unlike using vLLM, it<strong> </strong>allows the system to share tokens with another <strong>beam candidate </strong>to increase utilization.</li><li><strong>Swapping</strong>: Like, OS memory swapping. <strong>vLLM </strong>will transfer the evict block into CPU memory.</li></ol><h3>Demo</h3><p>This section demonstrates how to serve LLM via vLLM. The VM specification setup is <strong>A100 40g</strong> to test with <strong>Llama-2–13b-hf-chat</strong></p><h4>Compare between vLLM and Hugging face</h4><p>To test memory usage between <strong>vLLM</strong> and <strong>Hugging Face</strong>,<strong> </strong>this example will test one example request and then monitor GPU usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*c025rb6qtCdVhFo8yemAPA.png" /><figcaption>Fig. 8. GPU usage when inferencing a LLM model via Hugging Face</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*gj_QAwp0o90BZ1Jx4Nl6JQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*g8smtf_SkOjygO8A_SmDrA.png" /><figcaption>Fig. 9. GPU usage when loading model LLM model via vLLM (Left), GPU usage when inferencing model LLM model via vLLM</figcaption></figure><p>From <strong>Figs. 8.</strong> and <strong>9,</strong> the result is quite the same, but there is a slight difference when inference is made with a hugging face, which will raise this error.</p><pre>WARNING:root:Some parameters are on the meta device device because they were offloaded to the cpu.</pre><p>Which indicates that VM is running out of GPU memory and needs more resource, so you could notice Hugging Face using CPU memory more than vLLM since it needs to allocate more memory, which leads to leakage of GPU memory due to reservation.</p><p><strong>Test code (HF)</strong></p><pre>from transformers import AutoModelForCausalLM,AutoTokenizer<br><br>MODEL_NAME=&quot;meta-llama/Llama-2-13b-hf&quot;<br>model = AutoModelForCausalLM.from_pretrained(<br>            MODEL_NAME, device_map=&quot;auto&quot;<br>        )<br>tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, padding_side=&quot;left&quot;)<br>prompt = &quot;&quot;&quot;What is Thailand&#39;s national food symbol.&quot;&quot;&quot;<br>model_inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br><br>input_length = model_inputs.input_ids.shape[1]<br>generated_ids = model.generate(**model_inputs, max_new_tokens=64)<br><br>print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])</pre><p><strong>Test code (vLLM)</strong></p><pre>from vllm import LLM, SamplingParams<br><br>prompts = [<br> &quot;What is Thailand&#39;s national food symbol.&quot;<br>]<br><br>sampling_params = SamplingParams(max_tokens=64)<br><br>llm = LLM(model=&quot;meta-llama/Llama-2-13b-chat-hf&quot;)<br><br>outputs = llm.generate(prompts, sampling_params)<br><br># Print the outputs.<br>for output in outputs:<br>    prompt = output.prompt<br>    generated_text = output.outputs[0].text<br>    print(f&quot;Prompt: {prompt!r}, Generated text: {generated_text!r}&quot;)</pre><h4>Serving as REST API</h4><p>vLLM already has built-in RestAPI by using FastAPI via a single command.</p><pre>python -m vllm.entrypoints.openai.api_server --model &quot;meta-llama/Llama-2-13b-chat-hf&quot; --dtype float16 --api-key &quot;test&quot;</pre><p>This endpoint is compatible with <strong>the OpenAI</strong> endpoint, so if your system integrates with OpenAI, you don’t need to change your request format or write a new API for vLLM to replace your existing LLM model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Bi2s16BwpHgwna_hIPwuag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*m_gX49MgRkGTN1mgvb1S-Q.png" /><figcaption>Fig. 10. Serving API via vLLM command (left), GPU memory usage (right)</figcaption></figure><p><strong>Fig. 10</strong> shows starting an API via a command and GPU memory usage, which I mentioned above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*VYTqMoVcyBJjArmIbskGIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*RJqD6i_ts1SPOa0E0Z1p2Q.png" /><figcaption>Fig. 11: Test a LLM request</figcaption></figure><p>From <strong>Fig. 11, </strong>illustrate the inference request by using the OpenAI format, whose code is shown below.</p><pre>from openai import OpenAI<br>client = OpenAI(<br>    base_url=&quot;http://localhost:8000/v1&quot;,<br>    api_key=&quot;test&quot;,<br>)<br><br>completion = client.chat.completions.create(<br>  model=&quot;meta-llama/Llama-2-13b-chat-hf&quot;,<br>  messages=[<br>    {&quot;role&quot;: &quot;user&quot;,&quot;content&quot;: &quot;What is Thailand&#39;s national food symbol.&quot;}<br>  ],<br>  temperature=0.2,<br>  max_tokens=64,<br>  top_p=1<br>)<br><br>print(completion.choices[0].message.content)</pre><h4>Load testing</h4><p>This load test may not be a proper setup, but I would like to point out the GPU usage part with vLLM, so it may not affect a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PErDj9j3FTPimKF-BZdueg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQyYzrKdS2ImP-_g4lcruA.png" /><figcaption>Fig. 12. Load test with same prompt on 1 users per second (left), Load test with same prompt on 10 users per second (right)</figcaption></figure><p>There is a slight difference in GPU memory usage from <strong>Fig. 12, </strong>since using the same prompt and vLLM will use a <strong>copy-on-write</strong> mechanism, which helps to utilize the KV cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4r5nwhG-skojXEZ_myOpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pf8nBFnMmiwB9TgBzz9bJA.png" /><figcaption>Fig. 13. Load test with random prompt on 1 users per second (left), Load test with random prompt on 10 users per second (right)</figcaption></figure><p>Next, load-test on a selected random prompt from the list. The GPU memory usage changes minimally, and the RPS is quite impressive with 4.68 requests per second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_joS4AQLi5Q1x_oRbOELyw.png" /><figcaption>Fig. 14. Load test with random prompt on 10 users/second with longer token</figcaption></figure><p>Let’s try with longer tokens (256 tokens). As a result, GPU memory rises modestly with fewer requests per second, which is acceptable since longer content needs more time to generate.</p><p><strong>Load test code</strong></p><pre>from locust import HttpUser, task<br>import json<br>import random<br><br>questions = [<br>    &quot;What is Thailand&#39;s national food symbol.&quot;,<br>    &quot;How to cook pad-thai&quot;,<br>    &quot;Recommended vacation spots in Thailand&quot;,<br>    &quot;Best mall in Bangkok&quot;,<br>    &quot;How to travel by public transport in Bangkok&quot;<br>]<br><br>class AskWithSameQuestion(HttpUser):<br>    @task<br>    def test(self):<br>        self.client.post(<br>            &quot;/v1/chat/completions&quot;,<br>            data=json.dumps(<br>                    {<br>                        &quot;model&quot;: &quot;meta-llama/Llama-2-13b-chat-hf&quot;,<br>                        &quot;messages&quot;: [<br>                            {&quot;role&quot;: &quot;user&quot;,&quot;content&quot;: &quot;What is Thailand&#39;s national food symbol.&quot;}<br>                        ],<br>                        &quot;temperature&quot;: 0.5,<br>                        &quot;max_tokens&quot;: 64,<br>                        &quot;top_p&quot;: 1<br>                    }<br>                ),<br>            headers={<br>                &quot;Content-Type&quot;: &quot;application/json&quot;,<br>                &quot;Authorization&quot;: f&quot;Bearer test&quot;,<br>            }<br>        )<br><br>class AskRandomWithSameQuestion(HttpUser):<br>    @task<br>    def test(self):<br>        question = random.choice(questions)<br>        self.client.post(<br>            &quot;/v1/chat/completions&quot;,<br>            data=json.dumps(<br>                    {<br>                        &quot;model&quot;: &quot;meta-llama/Llama-2-13b-chat-hf&quot;,<br>                        &quot;messages&quot;: [<br>                            {&quot;role&quot;: &quot;user&quot;,&quot;content&quot;: question}<br>                        ],<br>                        &quot;temperature&quot;: 0.5,<br>                        &quot;max_tokens&quot;: 256,<br>                        &quot;top_p&quot;: 1<br>                    }<br>                ),<br>            headers={<br>                &quot;Content-Type&quot;: &quot;application/json&quot;,<br>                &quot;Authorization&quot;: f&quot;Bearer test&quot;,<br>            }<br>        )</pre><h4>Additional Features</h4><ol><li><strong>Continuous batching</strong> : vLLM already has built-in continuous batching, which utilizes more memory and increases token pre-seconds. You could get more information about this in my previous article, <a href="https://medium.com/@RTae/leveraging-ray-and-vertex-ai-for-llmops-6b169f65ff3a">Recap DevFest Cloud Bangkok 2023 : Leveraging Ray and Vertex AI for LLMOps</a>.</li><li><strong>BentoML</strong>: If your system is based on BentoML, vLLM already integrates with <strong>BentoML </strong>seamlessly, and you could get more detail from this <a href="https://docs.bentoml.org/en/latest/use-cases/large-language-models/vllm.html">article</a>.</li><li><strong>Distribute inference </strong>:<strong> </strong>Distribute system ? vLLM supports distributed inference with <a href="https://docs.vllm.ai/en/latest/serving/distributed_serving.html">Ray</a>.</li></ol><h3><strong>Summary</strong></h3><p>vLLM shows that making fantastic stuff doesn’t require fancy stuff by using simple concepts that we have already applied to computer systems for a decade. This framework has tremendous improvements in GPU memory usage and extends a variety of benefits with the PageAttention technique. By reducing the usage of KV cache, the system was able to handle a larger load and inference faster.</p><p>Last year, the vLLM team presented their work at Ray Summit 2023, where you could get more ideas and inspiration about their work by watching this video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5ZlavKF_98U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5ZlavKF_98U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5ZlavKF_98U%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/55828d6f6a3683e67d885b5bf7c4f3c3/href">https://medium.com/media/55828d6f6a3683e67d885b5bf7c4f3c3/href</a></iframe><h3>Reference</h3><ul><li><a href="https://www.youtube.com/watch?v=80bIUggRJf4">https://www.youtube.com/watch?v=80bIUggRJf4</a></li><li><a href="https://arxiv.org/abs/2309.06180">https://arxiv.org/abs/2309.06180</a></li><li><a href="https://blog.vllm.ai/2023/06/20/vllm.html">https://blog.vllm.ai/2023/06/20/vllm.html</a></li><li><a href="https://medium.com/@zaiinn440/autoregressive-models-for-natural-language-processing-b95e5f933e1f">https://medium.com/@zaiinn440/autoregressive-models-for-natural-language-processing-b95e5f933e1f</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3713009fb73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cj-express-tech-tildi/how-does-vllm-optimize-the-llm-serving-system-d3713009fb73">How does vLLM optimize the LLM serving system?</a> was originally published in <a href="https://medium.com/cj-express-tech-tildi">CJ Express Tech (TILDI)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Ray and Vertex AI for LLMOps]]></title>
            <link>https://medium.com/@RTae/leveraging-ray-and-vertex-ai-for-llmops-6b169f65ff3a?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b169f65ff3a</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[rays]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 02:58:43 GMT</pubDate>
            <atom:updated>2024-02-24T02:58:43.335Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Recap </strong>DevFest Cloud Bangkok 2023 :<strong> </strong>Leveraging Ray and Vertex AI for LLMOps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eq55zzKPLRPUq2HFX3IS3w.png" /></figure><p>After introducing the Ray framework in <a href="https://gdg.community.dev/events/details/google-gdg-cloud-bangkok-presents-devfest-cloud-bangkok-2023/"><strong>DevFest Cloud Bangkok 2023</strong></a>, I would like to recap and summarise my presentation through this article. In late 2023, GCP announced a new integration between Ray and VertexAI, which GCP named <a href="https://cloud.google.com/vertex-ai/docs/open-source/ray-on-vertex-ai/overview"><strong>Ray on VertexAI</strong></a>. This new service allowed Ray’s user to develop software in the VertexAI eco-system without losing the benefit of Ray. In addition, I would like to recap each part of my talk and demonstrate with <strong>Ray on VertexAI</strong> in the <strong>LLMOps</strong> part.</p><h4>Table of content</h4><ul><li>What is Ray?</li><li>Benefits of using Ray</li><li>Why Ray on Vertex AI?</li><li>Demo with LLMOps</li><li>Bonus : Recap from Ray Summit 2023</li></ul><h4>What is Ray?</h4><p>Ray is a framework for helping simplify distributed computing workloads which it allows developer users to focus on developing software to solve business problems and lets the framework handle a parallel task by using Python Native. Beside that, Ray is providing <strong>heterogeneous clusters, auto-scaling, and executor lifecycle management, </strong>so users wouldn’t need to manage cluster and scaling stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DG7bpeW1FqZQ-S6F" /><figcaption>Figure 1 — Ray Component</figcaption></figure><p>Moreover, Ray includes the <strong>Ray AI Runtime,</strong> or <strong>Ray</strong> <strong>AIR</strong>, which is a rich set of libraries that integrate into the system with the distribute computing feature. Therefore, these libraries increase productivity for the product life cycle, which could be separated into four categories.</p><ol><li><strong>Ray dataset</strong>: Ray provides a function to load and process data with a user function by using the Ray load data function, which supports distribution processing data.</li><li><strong>Ray training</strong>: Provide a wrapper to allow developer code to be a distribution function without changing the code. As a result, developers focus on training model code without managing a distributed training system.</li><li><strong>Ray tuning</strong>: Tuning an AI/ML model has been a challenging task for a decade due to the fact that finding an optimal value for the model is a complicated task. For instance, adjusting one hyperparameter could open a new experiment, so the number of experiments would grow tremendously.</li><li><strong>Ray serving: </strong>To be an end-to-end integration Ray provides a serving library that helps users deploy AI models with this library without modifying the code since it provides a wrapper function to encapsulate your function and then serve as an API.</li></ol><h4>Benefits of using Ray</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kQA8jrYBc7Afyq40" /><figcaption>Figure 2— Ray State</figcaption></figure><p>Ray isn’t the first framework to solve a distributed task. There are many distributed frameworks, such as Spark, Dash, Celery, etc. Why should you consider Ray?</p><ol><li>Powerful primitive for distributed computing since Ray provides a remote task distribution and remote object store due to distributed system design.</li><li>Heterogeneous clusters, auto-scaling, and executor lifecycle management are in the framework, so developers focus on developing machine learning rather than bothering with a cluster configuration.</li><li>With rich, famous ML library integration, this benefit allowed users to integrate with their favourite tools. As a result, developers would be confronted with their environment.</li><li>Support Kubernetes operators (KubeRay), since this framework is based on distributed computing design and development based on Kubernetes, so it allows users to develop software by using Kubernetes operators.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/0*K1N0meFe3bLwOE45" /><figcaption>Figure 3— Example library that support in Ray</figcaption></figure><h4>Why Ray on Vertex AI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y_-nqsASbX2-akS0" /><figcaption>Figure 4 — Ray on Vertex AI Component</figcaption></figure><ol><li>Cost and time savings to maintain infrastructure for Ray, since provision and maintenance of Ray infrastructure might be a tedious task if you don’t have a platform engineer or an engineer who has the knowledge to maintain it. As a result, Vertex AI provides a Ray infrastructure for you to develop your software</li><li>Being a GCP product has benefits in integration with other GCP products, such as cloud logging, cloud monitoring, Big Query, and GCS. This benefit increase productivity for developing software in the GCP</li><li>The library and API are the same as self-hosting Ray, since this is <strong>Ray on the Vertex AI!!</strong></li></ol><h4>Demo with LLMOps</h4><p>For this demonstration, I will show the training parts of the LLMOps which you could use these concept for continuous training (CT) in your pipeline by sending a training task into to Ray cluster from your pipeline that illustrate the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLpS4DJR0LdeccXciewPrg.png" /><figcaption>Figure 5 — Train LLM model</figcaption></figure><p>For the LLM model, we will not train it but fine-tune it since the LLM model has a large model architect with huge training data. As a result, building a train model from scratch won’t be a good idea. This article will select a foundation model and fine-tune it using custom data by using Ray.</p><ul><li><strong>Load dataset: </strong>Load data from Hugging Face by using Ray Dataset to load.</li><li><strong>Preprocess dataset: using the</strong> Ray dataset function to tokenize data for the preprocessing process.</li><li><strong>Fine-tune model: </strong>Using the Ray train function with the train function from Hugging Face to create a fine-tune foundation model.</li><li><strong>Tune model: </strong>Ray provides a tuning function for hyperparameter tuning the model.</li></ul><p><strong>Setup Ray cluster on Ray on VertexAI</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOMsJeHDmx_WbyX3UzP6yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHM4ApFXiW9rME-h3OPTqg.png" /><figcaption>Figure — 6 Create cluster page</figcaption></figure><p>By searching for “<strong>Ray on VertexAI</strong>” and selecting the desired region, then “<strong>CREATE CLUSTER</strong>” it will pop up a page for creating one cluster. On the create page, add the cluster’s name and metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrHHpRZoKmjQapZqtI_INg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESoeA8V5fg5Gmijv6vXxvg.png" /><figcaption>Figure — 7 Cluster config page</figcaption></figure><p>For compute setting, we will be able to configure a compute setting, which, in the case I select A100 for 2 GPUs, so you may wonder why I need a lot of GPU. This is normal for fine-tuning models, which is why I don’t recommend training the foundation model from scratch. If you do it from scratch, you will lose the context of the training data, which may not be beneficial for your application. After that, we need to set up a network with private service access to allow the cluster to access GCP services.</p><p>When a cluster is provisioned, we could use a Google Colab Enterprise to access your cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CUYMkCrscP7POgonHaVcw.png" /><figcaption>Figure — 8 Access through Google Colab Enterprise</figcaption></figure><p><strong>Setup dependency and connection</strong></p><p>First, we need to setup a dependency and cluster connection to send a job from local to cluster, which you could follow the script below</p><pre>%pip install peft==0.5.0<br>%pip install datasets==2.12.0 bitsandbytes==0.40.0 einops==0.6.1 trl==0.4.7<br>%pip install torch==2.1.0 accelerate==0.21.0 tokenizers transformers==4.38.1<br>%pip install pyarrow==8.0.0<br>%pip install protobuf==3.20.0<br>%pip install xformers==0.0.22</pre><p>Next, we need to import the required dependency and connect with the Vertex Library.</p><pre>import ray<br>import torch<br>import transformers<br>import warnings<br>import numpy as np<br>from huggingface_hub import login<br>from datasets import load_dataset<br>from typing import Any, Dict, List, Optional<br>from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments, Trainer<br>from peft import prepare_model_for_kbit_training, LoraConfig, get_peft_model<br>from ray.util.spark import setup_ray_cluster, shutdown_ray_cluster, MAX_NUM_WORKER_NODES<br>from ray.data.preprocessors import BatchMapper<br>from google.cloud import aiplatform<br>from google.cloud.aiplatform.preview import vertex_ray<br><br>transformers.set_seed(42)<br>warnings.simplefilter(&quot;ignore&quot;)<br>aiplatform.init(project=&#39;&lt;PROJECT_ID&gt;&#39;, location=&#39;us-central1&#39;)</pre><p>After that, we need to initialise the cluster connection to allow Ray to send a task to the cluster, so we could use the Ray cluster resource for processing our task without inheriting your local machine. Moreover, this connection could install a dependency or set up an environment variable in our cluster.</p><pre># Initialize connection to the Ray on Vertex AI Cluster<br>if ray.is_initialized():<br>   ray.shutdown()<br><br>ray.init(<br>    address=&#39;vertex_ray://projects/311317147984/locations/us-central1/persistentResources/cluster-20240224-082335&#39;,<br>    runtime_env={<br>      &quot;pip&quot;: [<br>          &quot;transformers==4.38.1&quot;,<br>          &quot;tokenizers==0.15.1&quot;,<br>          &quot;torch==2.0.1&quot;,<br>          &quot;peft==0.5.0&quot;,<br>          &quot;datasets==2.12.0&quot;,<br>          &quot;bitsandbytes==0.40.0&quot;,<br>          &quot;einops==0.6.1&quot;,<br>          &quot;trl==0.4.7&quot;,<br>          &quot;accelerate==0.21.0&quot;,<br>          &quot;pyarrow==8.0.0&quot;,<br>          &quot;protobuf==3.20.0&quot;,<br>          &quot;xformers==0.0.22&quot;,<br>          &quot;ipython&quot;<br>      ],<br>      &quot;env_vars&quot;: {<br>          &quot;PYTORCH_CUDA_ALLOC_CONF&quot;: &quot;max_split_size_mb:512&quot;<br>      }<br>    }<br>)</pre><p><strong>Load and prepare dataset</strong></p><p>In this demo, I will use the metal health counselling conversion from Hugging Faces as fine-tuned data. In this step, we could download a dataset by using the Hugging Face library, which is the same as Hugging Face’s document.</p><pre>dataset_name = &quot;Amod/mental_health_counseling_conversations&quot;<br>hf_dataset = load_dataset(dataset_name)</pre><p>Next, we need to create a preprocess function to fine-tune a LLM model, which requires two processes.</p><ol><li>Format into prompt template</li><li>Tokenize a template</li></ol><p>For the prompt template, I created a prompt template for a mental health case, which is shown in the code below.</p><pre>INTRO_BLURB = &quot;Below is a question and response about mental health question. Write a response that appropriately completes the request.&quot;<br>QUESTION_KEY = &quot;&lt;start_of_turn&gt;user&quot;<br>END_USER_KEY = &quot;&lt;end_of_turn&gt;&quot;<br>RESPONSE_KEY = &quot;&lt;start_of_turn&gt;model&quot;<br><br>PROMPT_FORMAT = &quot;&quot;&quot;{intro}<br><br>{question_key}<br>{question}{end_key}<br><br>{response_key}<br>{response}<br>&quot;&quot;&quot;.format(<br>  intro=INTRO_BLURB,<br>  question_key=QUESTION_KEY,<br>  question=&quot;{question}&quot;,<br>  response_key=RESPONSE_KEY,<br>  response=&quot;{response}&quot;,<br>  end_key=END_USER_KEY<br>)<br><br><br>def apply_prompt_template(data):<br>  question = data[&quot;Context&quot;]<br>  response = data[&quot;Response&quot;]<br><br>  full_prompt = PROMPT_FORMAT.format(question=question, response=response)<br><br>  return { &quot;text&quot;: full_prompt }<br><br>def generate_prompt(prompt):<br>    return apply_prompt_template(prompt)</pre><p>Next, we need to tokenize a prompt by using the Hugging Face function and Ray. For tokenizers, I will use <strong>Gemma-2b-it </strong>as a tokenizer and fine-tune model. As a result, we may create a custom function and then use the <strong>BatchMapper </strong>function from the <strong>Ray Dataset</strong> to process the data in the training pipeline.</p><pre>model_name = &quot;google/gemma-2b-it&quot;<br>hf_token = &#39;&lt;HUGGING_FACE_TOKEN&gt;&#39;<br>max_length = 2048<br>batch_size = 4096<br><br>login(token=hf_token)<br><br>tokenizer = AutoTokenizer.from_pretrained(<br>    model_name,<br>    trust_remote_code=True,<br>    padding_side=&quot;left&quot;,<br>    add_eos_token=True,<br>    add_bos_token=True<br>)<br>tokenizer.pad_token = tokenizer.eos_token<br><br>def preprocess_function(batch: Dict[str, Any]) -&gt; Dict[str, Any]:<br>    result = tokenizer(<br>        list(batch[&quot;text&quot;]),<br>        max_length=max_length,<br>        truncation=True,<br>        padding=&quot;max_length&quot;,<br>        return_tensors=&quot;np&quot;,<br>    )<br><br>    result[&quot;labels&quot;] = result[&quot;input_ids&quot;].copy()<br><br>    return dict(result)<br><br>batch_preprocessor = BatchMapper(preprocess_function, batch_format=&quot;pandas&quot;, batch_size=batch_size)<br><br>ray_train_dataset = ray.data.from_huggingface(hf_train_dataset)</pre><p><strong>Fine-tune model</strong></p><p>To fine-tune <strong>Gemma-2b-it</strong>, we could follow a document from Hugging Face to start training an LLM model. Moreover, integration with Ray requires writing a function that is compatible with Ray, which you could follow through the Ray document, as shown in the code below.</p><pre>def trainer_init_per_worker(<br>    train_dataset: ray.data.Dataset,<br>    eval_dataset: Optional[ray.data.Dataset] = None,<br>    **config,<br>) -&gt; Trainer:<br>    device = torch.device(&quot;cuda&quot;)<br><br>    login(token=config.get(&quot;hf_token&quot;))<br><br>    tokenizer = AutoTokenizer.from_pretrained(<br>        pretrained_model_name_or_path=config.get(&quot;model_name&quot;),<br>        trust_remote_code=True,<br>        padding_side=&quot;left&quot;,<br>        add_eos_token=True,<br>        add_bos_token=True<br>    )<br>    tokenizer.pad_token = tokenizer.eos_token<br><br>    num_gpus = torch.cuda.device_count()<br>    max_memory = config.get(&quot;max_memory&quot;)<br><br>    bnb_config = BitsAndBytesConfig(<br>        load_in_4bit=True,<br>        bnb_4bit_use_double_quant=True,<br>        bnb_4bit_quant_type=&quot;nf4&quot;,<br>        bnb_4bit_compute_dtype=torch.bfloat16<br>    )<br><br>    model = AutoModelForCausalLM.from_pretrained(<br>        pretrained_model_name_or_path=config.get(&quot;model_name&quot;),<br>        device_map={&#39;&#39;:torch.cuda.current_device()}, # fix for &gt;3 GPUs<br>        quantization_config=bnb_config,<br>        max_memory={i: max_memory for i in range(num_gpus)},<br>        trust_remote_code=True<br>    )<br><br>    model.gradient_checkpointing_enable()<br>    model = prepare_model_for_kbit_training(model)<br><br>    peft_config = LoraConfig(<br>        lora_alpha=config.get(&quot;lora_alpha&quot;, 16),<br>        lora_dropout=config.get(&quot;lora_dropout&quot;, 0.1),<br>        r=config.get(&quot;lora_r&quot;, 64),<br>        bias=&quot;none&quot;,<br>        task_type=&quot;CAUSAL_LM&quot;,<br>        target_modules=[<br>                &quot;q_proj&quot;,<br>                &quot;k_proj&quot;,<br>                &quot;v_proj&quot;,<br>                &quot;o_proj&quot;,<br>                &quot;gate_proj&quot;,<br>                &quot;up_proj&quot;,<br>                &quot;down_proj&quot;,<br>                &quot;lm_head&quot;,<br>            ] # Choose all linear layers from the model<br>    )<br><br>    model = get_peft_model(model, peft_config)<br><br>    training_arguments = TrainingArguments(<br>        output_dir=&quot;checkpoints&quot;,<br>        per_device_train_batch_size=config.get(&quot;per_device_train_batch_size&quot;, 1),<br>        gradient_accumulation_steps=config.get(&quot;gradient_accumulation_steps&quot;, 1),<br>        optim=&quot;paged_adamw_8bit&quot;,<br>        save_steps=config.get(&quot;save_steps&quot;, 50),<br>        logging_steps=config.get(&quot;logging_steps&quot;, 50),<br>        learning_rate=config.get(&quot;learning_rate&quot;, 2e-4),<br>        bf16=False,<br>        fp16=True,<br>        max_grad_norm=0.3,<br>        max_steps=config.get(&quot;max_steps&quot;, 100),<br>        weight_decay=config.get(&quot;weight_decay&quot;, 0.001),<br>        logging_strategy=&quot;steps&quot;,<br>        save_strategy=&quot;steps&quot;,<br>        warmup_ratio=config.get(&quot;warmup_ratio&quot;, 0.03),<br>        group_by_length=False,<br>        lr_scheduler_type=config.get(&quot;lr_scheduler_type&quot;, &quot;constant&quot;),<br>        ddp_find_unused_parameters=False,<br>        push_to_hub=False,<br>        disable_tqdm=False,<br>    )<br><br>    trainer = Trainer(<br>        model=model,<br>        train_dataset=train_dataset,<br>        args=training_arguments,<br>        tokenizer=tokenizer,<br>    )<br>    model.config.use_cache = False<br><br>    return trainer</pre><p>After preparing training code, we need to configure a Ray train, such as the dataset, train function, preprocess function, and scaling configuration.</p><pre>from ray.air.config import RunConfig, ScalingConfig, CheckpointConfig<br>from ray.train.huggingface import HuggingFaceTrainer<br><br>trainer = HuggingFaceTrainer(<br>    trainer_init_per_worker=trainer_init_per_worker,<br>    trainer_init_config={<br>        &quot;model_name&quot;: model_name,<br>        &quot;hf_token&quot;: hf_token,<br>        &quot;max_memory&quot;: max_memory,<br>        &quot;logging_steps&quot;: logging_steps,<br>        &quot;save_steps&quot; : save_steps,<br>        &quot;max_steps&quot;: max_steps<br>    },<br>    scaling_config=ScalingConfig(<br>        num_workers=num_workers,<br>        use_gpu=use_gpu,<br>        resources_per_worker={&quot;GPU&quot;: num_gpu_per_worker, &quot;CPU&quot;: resource_per_worker_int}<br>    ),<br>    datasets={<br>        &quot;train&quot;: ray_train_dataset<br>    },<br>    run_config=RunConfig(<br>        checkpoint_config=CheckpointConfig(<br>            num_to_keep=1,<br>            checkpoint_score_attribute=&quot;loss&quot;,<br>            checkpoint_score_order=&quot;min&quot;,<br>        ),<br>        verbose=0<br>    ),<br>    preprocessor=batch_preprocessor<br>)<br><br><br></pre><p>After that, we could fine-tune model by using <strong>.fit()</strong> function</p><pre>result = trainer.fit()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4IlwsU6iyRdDFVyYs3YWQ.png" /><figcaption>Figure 9— Test fine tune model</figcaption></figure><p><strong>Hyperparameter tuning</strong></p><p>Next, to tune a hyperaprameter, we could use a package from Ray, which provides the same interface as Ray Train, as illustrated in the code below.</p><pre>from ray import tune<br>from ray.tune import Tuner<br>from ray.tune.schedulers.async_hyperband import ASHAScheduler<br><br>total_num_trials = 4<br>max_tune_steps = 20<br><br>tuner = Tuner(<br>    trainer,<br>    param_space={<br>        &quot;trainer_init_config&quot;: {<br>            &quot;learning_rate&quot;: tune.choice([1e-5, 1e-4, 1e-3, 1e-2]),<br>            &quot;max_steps&quot;: tune.choice([5, 10, 15, max_tune_steps]),<br>        }<br>    },<br>    tune_config=tune.TuneConfig(<br>        metric=&quot;loss&quot;,<br>        mode=&quot;min&quot;,<br>        num_samples=total_num_trials,<br>        scheduler=ASHAScheduler(<br>            max_t=max_tune_steps,<br>        ),<br>    ),<br>    run_config=RunConfig(<br>        checkpoint_config=CheckpointConfig(<br>            num_to_keep=1,<br>            checkpoint_score_attribute=&quot;loss&quot;,<br>            checkpoint_score_order=&quot;min&quot;,<br>        )<br>    ),<br>)</pre><p>Using same method as <strong>Ray train</strong></p><pre>tune_results = tuner.fit()</pre><p>And we could get a result by using this script</p><pre>tune_results_df = tune_results.get_dataframe().sort_values(&quot;loss&quot;)<br>best_result = tune_results.get_best_result()<br><br>print(best_result.checkpoint)<br>print(best_result.metrics)</pre><h4>Bonus : Recap from Ray Summit 2023</h4><p>Bonus!! In September 2023, Ray arranged an event called <a href="https://raysummit.anyscale.com/">Ray Summit 2023,</a> which invited amazing speakers around the world, and I would like to share some interesting sessions.</p><p><strong>Ray LLM</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71kxLJyQHGhQ_peL" /><figcaption>Figure 10— iRay LLM from Any Scale Team — <a href="https://www.youtube.com/watch?v=TJ5K1CO9Wbs">https://www.youtube.com/watch?v=TJ5K1CO9Wbs</a></figcaption></figure><p>Ray-LLM: Behind the screens of top-tier companies such as OpenAI, Uber, and Cohere, which help deploy LLM models, is <a href="https://www.anyscale.com/">Anyscale</a>. This platform allowed developers to serve LLM models, and it was developed by the Ray Team, but I would like to share some details about their tool, <a href="https://github.com/ray-project/ray-llm">Ray-LLM</a>. This tool solves a technical problem when serving the LLM model, which could be divided into three issues.</p><ul><li><strong>Auto-scaling and serving the right GPU:</strong>Managing a workload or node for auto-scaling is a tedious task, but Ray could solve this task easily and select the right GPU for the model due to the fact that serving multiple models with a variety of sizes using a fixed size of GPU wouldn’t be a good idea.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYKnHsXK_pxv43ZxUTQi_Q.png" /><figcaption>Figure 11— Ray LLM from Any Scale Team — <a href="https://www.youtube.com/watch?v=TJ5K1CO9Wbs">https://www.youtube.com/watch?v=TJ5K1CO9Wbs</a></figcaption></figure><ul><li><strong>Continuous batching: </strong>GPUs are underutilised with native batching with different word sequences, but this method will concatenate new input sequence tokens into the end of the token batch to fill the batch sequence, which increases the throughput of the system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxXWE1Ha-r_R-xsTWuISFA.png" /><figcaption>Figure 12 — Speculative decoding</figcaption></figure><ul><li><strong>Speculative decoding: </strong>This method uses a small model to speculate the K token ahead and then a large model to verify, and it will emit a token if the token isn’t correct. These methods allow for faster forward passes per token, which reduces latency since large models only verify and can do it in parallel.</li></ul><p><strong>Hybrid routing</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rS0AxOEHIsVB9jtPpYvAJg.png" /><figcaption>Figure 13 — Developing and Serving RAG-Based LLM in Production — <a href="https://www.youtube.com/watch?v=YO9jYy-HIRY">https://www.youtube.com/watch?v=YO9jYy-HIRY</a></figcaption></figure><p>Another interesting technique is using a supervised classifier to classify queries that feed into the model and then select a suitable model before feeding into the LLM. This method helps to create agents based on the LLM since each LLM has its own specificity for each task, so it could be a better idea to let the model that has more context answer it.</p><h4>Summary</h4><p>In this article, I provide a benefit by using Ray with AI/ML projects, which you could apply to the LLMOps concept or MLOps since Ray gives flexibility to the developer to allow integration between framework and encapsulate your function as a task to run in the cluster as a distribute computed function. Although I only demonstrate the train model part of the LLMOps lifecycle, in the following article I’d like to discuss how to deploy a LLM model into production using <strong>Ray</strong> or <strong>BentoML</strong> with <strong>vLLM</strong>.</p><h4>Reference</h4><ul><li><a href="https://medium.com/google-cloud/ray-on-vertex-ai-lets-get-it-started-7a9f8360ea25">https://medium.com/google-cloud/ray-on-vertex-ai-lets-get-it-started-7a9f8360ea25</a></li><li><a href="https://huggingface.co/docs/transformers/en/tasks/language_modeling">https://huggingface.co/docs/transformers/en/tasks/language_modeling</a></li><li><a href="https://huggingface.co/docs/peft/en/index">https://huggingface.co/docs/peft/en/index</a></li><li><a href="https://huggingface.co/google/gemma-7b-it">https://huggingface.co/google/gemma-7b-it</a></li><li><a href="https://huggingface.co/datasets/Amod/mental_health_counseling_conversations/viewer">https://huggingface.co/datasets/Amod/mental_health_counseling_conversations/viewer</a></li><li><a href="https://www.youtube.com/watch?v=TJ5K1CO9Wbs">https://www.youtube.com/watch?v=TJ5K1CO9Wbs</a></li><li><a href="https://www.youtube.com/watch?v=YO9jYy-HIRY">https://www.youtube.com/watch?v=YO9jYy-HIRY</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b169f65ff3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy machine learning at scale with Yatai]]></title>
            <link>https://medium.com/cj-express-tech-tildi/deploy-machine-learning-at-scale-with-yatai-2671b56d0c32?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2671b56d0c32</guid>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 09:49:46 GMT</pubDate>
            <atom:updated>2023-09-19T05:06:46.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGTnaGm9dhdE-6NDvkvyCQ.png" /></figure><p>Hi, my name is Tae, and I am a Machine Learning Engineer (MLE) from CJ Express Tech (TILDI). I wrote this article to share knowledge about Yatai, which is a machine learning platform for deploying machine learning models. This tool is part of the deployment phase of the MLOps life cycle; therefore, it assists MLE in deploying machine learning at scale. For example, Yatai can manage an ML model version and deploy a service with large distribution support. As a result, this article will describe Yatai, its features, and the demo.</p><h3>Table of content</h3><ul><li>What is BentoML?</li><li>What is Yatai?</li><li>Yatai Feature</li><li>Demo</li><li>Flows of the deployment</li></ul><h3>What is BentoML?</h3><p>On their website, they said, “BentoML’s comprehensive toolkit for AI application development provides a unified distribution format that features a simplified AI architecture and supports deployment anywhere”. Therefore, BentoML is a simplified version of the package for ML and AI models. For more clarity, you could take a look at the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Wtrxpoo_xwIH9q3" /><figcaption>Bento Box from <a href="https://www.globalkitchenjapan.com/blogs/articles/would-you-like-to-have-one-for-special-occasions">Global Kitchen Kapan</a></figcaption></figure><p>When you need to deploy an ML or AI model, it consists of the model, library dependency, serving module, etc. Furthermore, it could be compared to a bento box set that contains a variety of foods that go together and can be eaten anywhere. Therefore, BentoML tries to wrap anything into one package and deploy it anywhere.</p><h3>What is Yatai?</h3><p>If you are a bento seller and need the store to sell bento, Yatai will solve your problem. Yatai in English means “stall”, It acts like a serving zone for our ML and AI models. If the system uses BentoML as a model wrapper, it will integrate seamlessly. As a result, you will have an end-to-end platform for building and serving models, like having your own bento store to cook bento and sell it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arn0Wfyuvu423cfrF_1C2A.png" /><figcaption><a href="https://docs.yatai.io/en/latest/concepts/architecture.html">Yatai Architecture</a></figcaption></figure><p>From the figure above, Yatai has two main functions, which are model registry and model deployment. Yatai has <strong>yatai-image-builder </strong>to convert the bento model from the registry into a Docker image for serving. Due to the fact that Yatai deploys in the Kubernetes cluster, it is mandatory to have a Docker image. After that, <strong>yatai-deployment </strong>will use this image to deploy into clusters with a separate interface (API) and runner (serving).</p><h3>Yatai Feature</h3><h4>Made for BentoML to deploy at scale</h4><p>Since the author of Yatai is the same as BentoML, this framework allows for seamless integration with BentoML.</p><h4>Management via UI or API</h4><p>Yatai has a web application UI for management or an API to integrate with another service in a system.</p><h4>Centralise registry</h4><p>Yatai has a built-in registry for storing the Bento registry since Bento is a wrapper of the ML/AI model before being deployed into a system.</p><h4>GitOp</h4><p>Yatai supports GitOp due to the fact that the systems are based on Kubernetes by using Kubernetes-native workflow via BentoDeployment CRD.</p><h4>Support observability stack</h4><p>Fully support integration with observability tools such as Prometheus, Grafrana, and Loki.</p><h3>Setup demo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iQO8oVMz5q6WbNdDyCfQQ.png" /><figcaption>Demo architecture</figcaption></figure><p>The architecture of this demo is shown in the image above, which could be separated into three parts with the code.</p><ol><li><strong>GitOps</strong>: Using Gitlab and AgroCd</li><li><strong>Yatai Platform</strong>: Build and deploy a machine-learning model</li><li><strong>Serving API</strong>: For serving the machine learning model as a</li></ol><p><strong>Code for this demo</strong></p><p><a href="https://github.com/RTae/yatai-demo">GitHub - RTae/yatai-demo</a></p><p>Furthermore, the content of this section could be divided into three main parts.</p><ol><li><strong>Infrastructure</strong>: the software’s infrastructure and this demo use GCP as a cloud provider.</li><li><strong>Service</strong>: Using a helm chart to provide services such as the Yatai platform, Serving service, and GitOp Tools</li><li><strong>Observability</strong>: An observability stack is provided in this demo by Prometus and Gafana.</li></ol><h4>1. Provision infrastructure</h4><p>Use Terraform to provision infrastructure by running the script below</p><pre>cd terraform<br>make apply ENV=dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*0IbNgObvV4-hSGeGUEyt6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*u3dAimj8N2iw82Wz7dT8sg.png" /><figcaption>Provison infra</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lc2_ONR5cnloFyLMfovkAw.png" /><figcaption>Provision result from GCP</figcaption></figure><p>Moreover, the components that Terraform provides are explained in the list below.</p><ul><li>Google artifact registry: Due to Kubernetes infrastructure, the system requires a registry for collecting docker images from the BentoML wrapper</li><li>Google Kubernetes cluster: For deploying services into the system for Yatai and serving APIs.</li></ul><h4>2. Deploy Service</h4><h4>2.1 Create a configuration in the cluster</h4><p>First, create two namespaces in Kubernetes, which are <strong>yatai-system</strong> and <strong>maine-coon</strong> for deploying Yatai and serving API, respectively, using the command below.</p><pre>kubectl create ns yatai-system<br>kubectl create ns maine-coon</pre><p>Then, create a database configuration since Yatai will use this component to store system data such as user, API key, and event log. On the other hand, this component could be replaced by using cloud SQL.</p><pre>export ROOT_USER=&quot;yatai&quot;<br>export ROOT_PASSWORD=&quot;123qweasdzxc&quot;<br>export ROOT_DB=&quot;yatai&quot;<br><br>kubectl create secret generic db-secret \<br>    --from-literal=ROOT_USER=&quot;$ROOT_USER&quot; \<br>    --from-literal=ROOT_PASSWORD=&quot;$ROOT_PASSWORD&quot; \<br>    --from-literal=ROOT_DB=&quot;$ROOT_DB&quot; \<br>    -n yatai-system</pre><p>Next, configure storage since Yatai provides a registry to store the BentoML registry.</p><pre>export STORAGE_USERNAME=&quot;yatai&quot;<br>export STORAGE_PASSWORD=&quot;123qweasdzxc&quot;<br>export STORAGE_SSL=false<br>export STORAGE_BUCKET_NAME=&quot;yatai&quot;<br><br>kubectl create secret generic storage-secret \<br>    --from-literal=STORAGE_USERNAME=&quot;$STORAGE_USERNAME&quot; \<br>    --from-literal=STORAGE_PASSWORD=&quot;$STORAGE_PASSWORD&quot; \<br>    --from-literal=STORAGE_SSL=&quot;$STORAGE_SSL&quot; \<br>    --from-literal=STORAGE_BUCKET_NAME=&quot;$STORAGE_BUCKET_NAME&quot; \<br>    -n yatai-system</pre><p>Then, create a configuration for accessing the Google artifact registry; this will be used by the Yatai system when building a Docker image.</p><pre>export REGISTRY_PASSWORD=&quot;`cat ./mlop.json | base64`&quot;<br><br>kubectl create secret generic docker-registry-secret \<br>    --from-literal=REGISTRY_PASSWORD=&quot;$REGISTRY_PASSWORD&quot; \<br>    -n yatai-system</pre><p>From the settings, the password is a service account, since this system uses a registry from GCP, which could use the service account that is attached to the GKE due to the fact that Terraform assigned the role of the service to <strong>Registry admin.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xrbpm8edPRUUrzHEizgs9A.png" /><figcaption>Result from config</figcaption></figure><h4>2.2 Deploy Yatai</h4><p>After several configurations, this part will explain details about components in the cluster such as GitOp, Proxy, and Yatai</p><p>First, we need to install Ingress to access the serving API and Yatai.</p><pre>helm install ingress-nginx ingress-nginx \<br>      --repo https://kubernetes.github.io/ingress-nginx \<br>      --namespace ingress-nginx \<br>      --create-namespace</pre><p>Next, for some simple SSL using cert-manager,</p><pre>helm repo add jetstack https://charts.jetstack.io<br>helm repo update<br>helm install cert-manager jetstack/cert-manager \<br>    --namespace cert-manager \<br>    --version v1.11.0 \<br>    --create-namespace \<br>    --set installCRDs=true<br><br>kubectl apply -f cert-manager/cert.yaml</pre><p>Then point your DNS record to the Nginx load balancer to access Yatai.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EY7JJZiIzTiI7DUsmkv2g.png" /><figcaption>DNS Config</figcaption></figure><p>Deploy Yatai by using the command below.</p><pre>helm dependency build./yatai-cluster<br><br>helm install yatai-cluster./yatai-cluster \<br>-f./yatai-cluster/values.yaml \<br>--namespace yatai-system</pre><p>The helm will install eight components, which are shown in the list below</p><ol><li><strong>Database</strong>: For storing data from the Yatai software</li><li><strong>Storage</strong>: As a bento registry to store Bento packages</li><li><strong>Yatai</strong>: Main software</li><li><strong>yatai-image-builder-crds</strong>: A CRD in Kubernetes for building an image from the Bento Package</li><li><strong>yatai-image-builder</strong>: For building Bento packages that integrate with the GitOps method.</li><li><strong>yatai-deployment-crds</strong>: A CRD in Kubernetes for deploying an image to cluster</li><li><strong>yatai-deployment</strong>: For deploying images to clusters that integrate with the GitOps method.</li><li><strong>Ingress</strong>: For accessing Yatai and Gafana from the public by using the Nginx ingress controller with cert-manager for self-cert.</li></ol><p>After installing a platform using Helm Chart, you could access the Yatai website, and the result is shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bt2rmQRiKlg3oIxqOg3bTQ.png" /></figure><p>Next, deploy ArgoCD for GitOps by using the script below.</p><pre>kubectl creates the namespace argocd<br>kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1tgLzj-Oe1EvuqVct77Tg.png" /><figcaption>ArgoCD deploy result</figcaption></figure><p>Next, you need to setup your Yatai account for the first time to login by going to &lt;<strong>YATAI_URL&gt;/setup?token=TOKEN, </strong>which you could get from an environment variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGa3psTno7qM1xzyy6PsiQ.png" /><figcaption>Setup</figcaption></figure><pre>kubectl -n yatai-system get secrets yatai-cluster-env -o jsonpath=&#39;.data.YATAI_INITIALIZATION_TOKEN}&#39; | base64 -d</pre><p>After that, you need to create a token to allow gitlab cicd to access your Yatai by selecting the api token option, or <strong>&lt; YATAI_URL&gt;/api_tokens, </strong>and creating an API with scope <em>API.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYRfu4qcwOwuI79oS9AHgg.png" /><figcaption>Generate token</figcaption></figure><p>Then, put a token into the Gitlab CICD variable, which I will name <strong>YATAI_TOKEN</strong> for this demo. Furthermore, you must create an endpoint for your Yatai, and in this demo, I setup ingress to proxy to <strong>yatai.rtae.cloud.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTgM_UxUpGNn3CbuBS4UAg.png" /><figcaption>Set Yatai token variable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jiOkINsr5yw8B4b8ljqrw.png" /><figcaption>Variables in gitlab CICD</figcaption></figure><p>Moreover, to create a GitOp flow, we need to set up an agent that will monitor your repository, which you could do by following the command to create an ArgoCD agent.</p><pre>kubectl apply -f argocd/deployment.yaml -n argocd</pre><p>Then, go to <strong>Settings -&gt; Repositories -&gt; Create a repository</strong> and choose a connection method that you prefer; this demo will use the http method, which requires an access token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zts-AhiZQdEBVubt9Kfspw.png" /><figcaption>Create repository</figcaption></figure><p>Then you setup the repositories, and ArgoCD will do its job to sync the helm chart from your repro. In this demo, I configure ArgoCD to sync Mainecoon Chart, which is an ML API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIGrjiou-EHFDD6X932OQw.png" /><figcaption>Mainecoon chart</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_8SdMEk3WlfFjhC7CJ1xQ.png" /><figcaption>Result from sync ArgoCD with Gitlab</figcaption></figure><p>Final, let’s test some deployment. I will change some details in the iris model and then push to Gitlab to create a CI tigger pipeline flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7v-ErIt0Dhcu1e9maQIuQ.png" /><figcaption>Change training config</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbDUY1RNiP7A9FMjsvZMbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nd0FXDT_3RmpvkbMVqnD-g.png" /><figcaption>Result from deploy service iris in Maincoon namespace</figcaption></figure><h4>3. Deploy Observability</h4><p>This part will explain the observability stack by installing Prometheus and Grafana first with the command below.</p><pre>helm repo add prometheus-community https://prometheus-community.github.io/helm-charts<br>helm repo update prometheus-community<br><br>helm install prometheus prometheus-community/kube-prometheus-stack \<br>-f./observability/prometheus-values.yaml \<br>--namespace yatai-system</pre><pre>helm repo add grafana https://grafana.github.io/helm-charts<br>helm repo update grafana<br><br>helm install grafana grafana/grafana \<br>-f./observability/grafana-values.yaml \<br>--namespace yatai-system</pre><p>Which you will get these results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4k19XvYl25CuopGFoQu--w.png" /><figcaption>Deploy pod from Prometheus and Grafana</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEOjzx3dFVKS2Hi01roO6g.png" /><figcaption>Example graph from Grafana</figcaption></figure><p>Next, we need to create agents that monitor our service by using the command below.</p><pre>kubectl apply -f observability/metric.yaml</pre><p>And create a dashboard in Grafana by using script below</p><pre>kubectl -n yatai-system create configmap bentodeployment-dashboard --from-file=./observability/bentodeployment-dashboard.json<br>kubectl -n yatai-system label configmap bentodeployment-dashboard grafana_dashboard=1<br><br>kubectl -n yatai-system create configmap bentofunction-dashboard --from-file=./observability/bentofunction-dashboard.json<br>kubectl -n yatai-system label configmap bentofunction-dashboard grafana_dashboard=1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PE0G7j-HQZUKJookjQ98QQ.png" /><figcaption>Dashboard to monitor Service in Yatai</figcaption></figure><h3>Flows of the deployment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVe5wqOqgynGG9S4Z7q0ZQ.png" /><figcaption>Flow of the deployment</figcaption></figure><p>The flow of the deployment is illustrated in the picture above and explained in the list below.</p><ol><li>Train model: This stage will handle the training part.</li><li>Pack model: It will pack the model into BentoML before uploading it into the Bento Registry in Yatai.</li><li>Update manifest config: Since we are using the GitOp method to deploy our model, it is required to update the helm chart config.</li><li>Build image: After ArgoCD syncs with configuration, the Bento Builder will build a Docker image from the Bento Model by using file configuration to pick a model from the registry.</li><li>Deploy model: Using Bento Deployment to deploy the Docker image from the previous step</li></ol><h3>Summary</h3><p>In this post, I show how to install Yatai and describe the benefits of utilizing Yatai during the deployment phase of the MLOps cycle. Because Yatai uses BentoML as its deployment backbone, this platform will seamlessly interact with it, giving it capabilities like GitOp, registration, and administration. Despite the fact that Yatai is not the only platform capable of doing this task, there are other ways that would fit the requirements, such as Kubeflow, MLFlow, and MLem from Literarive, which I might discuss in the future, that our team uses, or another part of MLOps.</p><h3>Reference</h3><ul><li><a href="https://bentoml.com/blog/yatai-10-model-deployment-on-kubernetes-made-easy">Yatai 1.0: Model Deployment On Kubernetes Made Easy</a></li><li><a href="https://github.com/bentoml/Yatai">GitHub - bentoml/Yatai: Model Deployment at Scale on Kubernetes 🦄️</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2671b56d0c32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cj-express-tech-tildi/deploy-machine-learning-at-scale-with-yatai-2671b56d0c32">Deploy machine learning at scale with Yatai</a> was originally published in <a href="https://medium.com/cj-express-tech-tildi">CJ Express Tech (TILDI)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s secure our Kafka component in the Kafka cluster with TLS!]]></title>
            <link>https://medium.com/cj-express-tech-tildi/lets-secure-our-kafka-component-in-the-kafka-cluster-with-tls-8b73cfc4aea1?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b73cfc4aea1</guid>
            <category><![CDATA[strimzi]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[tls]]></category>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 02:12:37 GMT</pubDate>
            <atom:updated>2023-03-21T07:13:20.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwR3HJCDCoJx_gfdqduXPQ.png" /><figcaption>Background image</figcaption></figure><p>Hi, my name is Tae, and I am a Machine Learning Engineer (MLE) from <strong>CJ Express Tech (TILDI)</strong>. I wrote this article to share knowledge about securing Kafka clusters with TLS. P’ Mil Data Engineer from my team introduced <a href="https://mesodiar.com/securing-kafka-with-tls-ssl-encryption-87816a82d6ca"><strong>Securing Kafka with TLS/SSL authentication</strong></a>, which gave a lot of ideas about TLS/SSL and why we should use it. As a result, this article will extend the detail about not using <strong>ANONYMOUS </strong>as<strong> </strong>a superuser to secure Kafka components such as Kafka UI, Kafka Connect, and Kafka Connector.</p><h3>Table of content</h3><ul><li>How do Microservices secure communication with mTLS?</li><li>Setup demo.</li><li>How to config Kafka UI to have a secure connection?</li><li>How to config Kafka connect to have a secure connection?</li><li>How to config the Schema registry to have a secure connection</li><li>Summary.</li></ul><h3>How do Microservices secure communication with mTLS?</h3><p>In general, most of the software architecture today uses microservice architecture for better performance. However, this architecture produces several problems, and the most common problem that software engineers always face is <strong>security</strong>. As a result, we use the TLS/SSL protocol to secure the communication between the services, but it is not just the TLS/SSL protocol; it is a <strong>mTLS,</strong> or <strong>mutual TLS.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBPASJf9-Wi2hVnwrALxEg.png" /><figcaption>What Is mTLS? (F5.com)</figcaption></figure><p><strong>mTLS </strong>is<strong> </strong>an extension implementation of TLS/SSL that identifies the client, not just the server. Since this concept is based on <a href="https://www.cloudflare.com/learning/security/glossary/what-is-zero-trust/"><strong>zero-trust security</strong></a>, the service must validate and identify both the server and the client to ensure the request is from an authorized client. As a consequence, we can control the damage from the service when this service is exploited and will not affect the service that is not associated with this service.</p><h3>Setup demo</h3><p>This article will show a simple setup for Kafka connect to transfer data from the database into object storage by using MySQL as source and GCS as sink in Google cloud service provider (GCP) which show in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*7psZMSIV7sU4JbKftk7jWQ.png" /><figcaption>Software architecture diagram</figcaption></figure><h4>1. Create service account for allowed Kafka connect to access GCS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*gE-UZcYZdpsmJ5R1uSeUNg.png" /><figcaption>Create service account</figcaption></figure><p>This service account allowed the Kafka connector inside Kafka Connect to access a bucket in the GCS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*BODIP_PcWAa4frk6yehxnw.png" /><figcaption>Generate key from service account</figcaption></figure><p>Next, we need to generate a service account key to use with the Kafka connector, and <strong>don’t forget to set this service account to access GCS</strong>; in my case, I configure my service account to be object admin since it’s a lab, but <strong>I not highly recommend to this in production</strong>, you must set permission to have properly fine gain.</p><h4>2. Provision a Kubernetes cluster</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*gI5bj60QmZzHlxZn47Pv1g.png" /><figcaption>GKE</figcaption></figure><p>We use a Kafka cluster, so we need to create a Kubernetes cluster to deploy our Kafka cluster, and <strong>I highly recommend provisioning this with a private VPC.</strong></p><h4>3. Provision database to be a source</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjJigL5WNFvqdYH-BUxdKw.png" /><figcaption>Create a database</figcaption></figure><p>Provision a MySQL 2019 database server to create a source for the Kafka connector. Moreover, this article provides a database with a development mode for cost-saving and private VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvmLi0vOnixZoWh8NCDgyg.png" /><figcaption>Create database instance</figcaption></figure><p>Next, we need to create a database instance to be used for data collection in this tutorial, which I will name “animal”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkieLGEk1_txkTJmix40xw.png" /><figcaption>Create table and seed some data</figcaption></figure><pre>create table random (<br> id INT,<br> name VARCHAR(50)<br>);<br><br>insert into random (id, name) values (1, &#39;Waterbuck, defassa&#39;);<br>insert into random (id, name) values (2, &#39;Dromedary camel&#39;);<br>insert into random (id, name) values (3, &#39;Sheep, american bighorn&#39;);<br>insert into random (id, name) values (4, &#39;Common zebra&#39;);<br>insert into random (id, name) values (5, &#39;Greater kudu&#39;);<br>insert into random (id, name) values (6, &#39;Pygmy possum&#39;);<br>insert into random (id, name) values (7, &#39;Kangaroo, black-faced&#39;);<br>insert into random (id, name) values (8, &#39;Cockatoo, slender-billed&#39;);<br>insert into random (id, name) values (9, &#39;Duck, blue&#39;);<br>insert into random (id, name) values (10, &#39;Elk, Wapiti&#39;);</pre><p>After that, create a new table in the database instance and seed some data into the table, which I name “random”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkQGAW2xX9IdRpco7v_KYw.png" /><figcaption>CDC</figcaption></figure><pre>EXEC msdb.dbo.gcloudsql_cdc_enable_db &#39;animal&#39;<br><br>EXEC sys.sp_cdc_enable_table<br>  @source_schema = N&#39;dbo&#39;,<br>  @source_name = N&#39;random&#39;,<br>  @role_name = N&#39;CDC&#39;<br><br>EXECUTE sys.sp_cdc_help_change_data_capture<br>  @source_schema = N&#39;dbo&#39;,<br>  @source_name = N&#39;random&#39;<br></pre><p>Last, create a change data capture (CDC) to let MySQL monitor changes from the table and store the data in a data warehouse, and this data will transfer into a Kafka broker by using Kafka connect.</p><h4>4. Provision GCS bucket as sink</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9PBMmZmIC3WKfH3Z4OG_g.png" /><figcaption>Create bucket</figcaption></figure><p>First, we need to provision a bucket to be a sink, which allows Kafka Connect to transfer data into this bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7EVppG2V89kgaN189cORow.png" /><figcaption>Create folder</figcaption></figure><p>Next, I create a folder named “animal” to be a sink folder to store data from the database when new data is ingressed into the system.</p><h4>6. Config Kafka cluster to allowed authorize user</h4><p>In this article, I provide a Helm chart for you, which you can follow by following the instructions in the README.md file; however, I will explain the configuration for you later in this article.</p><p><a href="https://github.com/RTae/kafka-cluster-tls">RTae/kafka-cluster-tls</a></p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: Kafka<br>metadata:<br>  name: cluster<br>  namespace: kafka<br>spec:<br>  kafka:<br>    version: 3.3.1<br>    replicas: 3<br>    listeners:<br>      - name: plain<br>        port: 9092<br>        tls: false<br>        type: internal<br>      - authentication:<br>          type: tls<br>        name: tls<br>        port: 9093<br>        tls: true<br>        type: internal<br>    authorization: # &lt;-- Config the allowe authorize user in this section to allowed<br>      superUsers:<br>      - CN=user<br>      type: simple<br>    config:<br>      default.replication.factor: 3<br>      inter.broker.protocol.version: &quot;3.3&quot;<br>      min.insync.replicas: 2<br>      offsets.topic.replication.factor: 3<br>      transaction.state.log.min.isr: 2<br>      transaction.state.log.replication.factor: 3<br>    storage:<br>      type: jbod<br>      volumes:<br>      - deleteClaim: false<br>        id: 0<br>        size: 100Gi<br>        type: persistent-claim<br>  zookeeper:<br>    replicas: 3<br>    storage:<br>      deleteClaim: false<br>      size: 100Gi<br>      type: persistent-claim<br>  entityOperator:<br>    topicOperator: {}<br>    userOperator: {}</pre><p>First, we need to create a list of authorized users to allow users to access the Kafka cluster in the <strong>authorization </strong>section. For example, I allowed the user name “user” to be a super user,” which means that in this article I use this user in every service, <strong>but the best practice is to create a user for each service. </strong>Moreover, the reason that I create only one user is that I want to simplify the flow so you can understand the component easier.</p><h4>7. Create Kafka user</h4><p>Next, we need to create a Kafka user to be the user for the components to access the Kafka cluster.</p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaUser<br>metadata:<br>  namespace: kafka<br>  name: user<br>  labels:<br>    strimzi.io/cluster: cluster<br>spec:<br>  authentication:<br>    type: tls<br>  authorization:<br>    acls:<br>    - operation: All<br>      resource:<br>        name: &#39;*&#39;<br>        patternType: literal<br>        type: topic<br>    - operation: All<br>      resource:<br>        name: &#39;*&#39;<br>        patternType: literal<br>        type: group<br>    - operation: All<br>      resource:<br>        type: cluster<br>    type: simple</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*JitAqA8p9gdu_InX4PRFfA.png" /></figure><h4>8. Generate certificate for the client</h4><p>After creating a Kafka user, we need to generate a certificate for the client so the server can validate the client using this certificate, and I create a Makefile to generate the script.</p><pre>SHELL := /usr/bin/env bash<br><br>help:<br> @echo &quot;&quot;<br> @echo &quot;Usage: make [TARGET] [OPTIONAL_ARGUMENTS]&quot;<br> @echo &quot;&quot;<br> @echo &quot;Where:&quot;<br> @echo &quot;  cluster=&lt;cluster_name&gt;         clustername&quot;<br> @echo &quot;  user=&lt;username&gt;                username&quot;<br> @echo &quot;  password=&lt;password&gt;            password&quot;<br> @echo &quot;&quot; <br> @echo &quot;example&quot;<br> @echo &quot;Usage: make create-secret cluster=datalake-k8s-staging user=user password=password&quot;<br> @echo &quot;Usage: make create-secret cluster=datalake-k8s-prod user=user password=password&quot;<br><br>create-secret:<br> mkdir -p  $(user)<br><br> ## generate file in local: ca.crt<br> kubectl get secret $(cluster)-cluster-ca-cert -n kafka -o jsonpath=&#39;{.data.ca\.crt}&#39; | base64 --decode &gt; $(user)/ca.crt<br><br> keytool -keystore $(user)/truststore.jks -storepass $(password) -alias CARoot -import -file $(user)/ca.crt -noprompt<br><br> ## generate file in local: user.crt, user.key, user.p12<br> kubectl get secret $(user) -n kafka -o yaml -o jsonpath=&#39;{.data.user\.crt}&#39; | base64 --decode &gt; $(user)/user.crt <br> kubectl get secret $(user) -n kafka -o yaml -o jsonpath=&#39;{.data.user\.key}&#39; | base64 --decode &gt; $(user)/user.key<br> openssl pkcs12 -export -in $(user)/user.crt -inkey $(user)/user.key  -password pass:$(password) -out $(user)/keystore.p12<br><br> ## create k8s secret as truststore keystore<br> kubectl create secret generic $(user)-auth-tls \<br>       --from-file=$(user)/truststore.jks \<br>       --from-file=$(user)/keystore.p12 \<br>       --from-literal=password=$(password) \<br>       -n kafka<br><br> @echo &quot;Cluser name: $(cluster)&quot; <br> @echo &quot;Username: $(user)&quot;<br> @echo &quot;Secret name which store certificate: $(user)-auth-tls&quot;<br><br> ##  generate file in local: pass<br> echo $(password) &gt; $(user)/pass</pre><p>Then, run this script below; it will generate a certificate and save it into Kubernetes’ secret store.</p><pre>make create-secret cluster=cluster user=user password=123qweasdzxc</pre><h3>How to config Kafka UI to have secure connection ?</h3><p>To allow Kafka UI to access the Kafka cluster with TLS/SSL, we need to use the client certificate that we generated in the previous section. Next, we need to mount a secret in volume <strong>(1)</strong> and use the certificate from this file <strong>(2)</strong>. Following that, in the Kafka UI, configure the “trust store”, “keystore” path, and password <strong>(3)</strong>, as shown below.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  namespace: kafka<br>  name: kafka-ui<br>  labels:<br>    app: kafka-ui<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: kafka-ui<br>  template:<br>    metadata:<br>      labels:<br>        app: kafka-ui<br>    spec:<br>      volumes: # &lt;- Create a volument which mount from secret (1)<br>        - name: kafka-user-auth-tls<br>          secret:<br>            secretName: user-auth-tls<br>      containers:<br>        - name: ui<br>          image: provectuslabs/kafka-ui:latest<br>          imagePullPolicy: IfNotPresent<br>          ports:<br>            - name: http<br>              containerPort: 8080<br>              protocol: TCP<br>          resources:<br>            limits:<br>              cpu: 500m<br>              memory: 256Mi<br>            requests:<br>              cpu: 100m<br>              memory: 128Mi<br>          volumeMounts: # &lt;- Mount secret volume into <br>            - name: kafka-user-auth-tls<br>              mountPath: &quot;/tmp&quot;<br>              readOnly: true<br>          env:<br>            - name: KAFKA_CLUSTERS_0_NAME<br>              value: &quot;cluster&quot;<br>            - name: KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS<br>              value: &quot;http://cluster-kafka-bootstrap:9093&quot;<br>            # NEED TO CONFIG THIS TO CONNECT WITH TLS (3)<br>            - name: KAFKA_CLUSTERS_0_PROPERTIES_SECURITY_PROTOCOL<br>              value: SSL<br>            - name: KAFKA_CLUSTERS_0_PROPERTIES_SSL_TRUSTSTORE_LOCATION<br>              value: /tmp/truststore.jks<br>            - name: KAFKA_CLUSTERS_0_PROPERTIES_SSL_TRUSTSTORE_PASSWORD<br>              valueFrom:<br>                secretKeyRef:<br>                  name: user-auth-tls<br>                  key: password<br>                  optional: false<br>            - name: KAFKA_CLUSTERS_0_PROPERTIES_SSL_KEYSTORE_LOCATION<br>              value: /tmp/keystore.p12<br>            - name: KAFKA_CLUSTERS_0_PROPERTIES_SSL_KEYSTORE_PASSWORD<br>              valueFrom:<br>                secretKeyRef:<br>                  name: user-auth-tls<br>                  key: password<br>                  optional: false<br>            # NEED TO CONFIG THIS TO CONNECT WITH TLS<br>            - name: KAFKA_CLUSTERS_0_KAFKACONNECT_0_NAME<br>              value: &quot;kafka_connect_source&quot;<br>            - name: KAFKA_CLUSTERS_0_KAFKACONNECT_0_ADDRESS<br>              value: &quot;http://kafka-connect-mssql-2019-source-cluster-connect-api:8083&quot;<br><br>            - name: KAFKA_CLUSTERS_0_KAFKACONNECT_1_NAME<br>              value: &quot;kafka_connect_sink&quot;<br>            - name: KAFKA_CLUSTERS_0_KAFKACONNECT_1_ADDRESS<br>              value: &quot;http://kafka-connect-gcs-sink-cluster-connect-api:8083&quot;</pre><p>You can test it by exposing the port and seeing if it works or not.</p><pre>cloud container clusters get-credentials kafka-cluster --zone asia-southeast1-a --project kafka-lab \<br> &amp;&amp; kubectl port-forward --namespace kafka $(kubectl get pod --namespace kafka --selector=&quot;app=kafka-ui&quot; --output jsonpath=&#39;{.items[0].metadata.name}&#39;) 8080:8080</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlsTvc9JHpFbqrjEl9bFMg.png" /><figcaption>Result from Kafka UI</figcaption></figure><h3>How to config Kafka connect to have secure connection ?</h3><p>In this article, we have two Kafka Connect, which are source and sink Connect, so we will have two configurations in each Kafka.</p><h4>1. Source connect</h4><p>To provision Kafka connect, we need to build custom images for our source, which is MySQL 2019, and you can build them with the Dockerfile and command below.</p><pre>FROM quay.io/strimzi/kafka:0.33.1-kafka-3.3.1<br>USER root:root<br><br>RUN mkdir -p /opt/kafka/plugins<br>ADD https://repo1.maven.org/maven2/io/debezium/debezium-connector-sqlserver/1.9.7.Final/debezium-connector-sqlserver-1.9.7.Final-plugin.tar.gz /opt/kafka/plugins<br>RUN cd /opt/kafka/plugins &amp;&amp; tar -xzf debezium-connector-sqlserver-1.9.7.Final-plugin.tar.gz &amp;&amp; rm -rf debezium-connector-sqlserver-1.9.7.Final-plugin.tar.gz**<br>USER 1001</pre><pre>docker build - t asia.gcr.io/kafka-lab/kafka-connect-mssql2019:1.0.0 .</pre><p>Next, to allow Kafka connect to communicate with Kafka cluster with TLS, we need to set a CA first <strong>(1)</strong> to be a verifier for the client to verify the certificate from the server, then <strong>(2)</strong> select a user secret for Kafka connect. In this setting, we do not need to generate our own certificate since Kafka Connect will handle it.</p><p>Moreover, we need to mount a secret into the volume in <strong>externalConfiguration</strong>, but in configuration, we need to add <strong>config.providers: directory</strong> and <strong>config.providers.directory.class: org.apache.kafka.common.config.provider.DirectoryConfigProvider,</strong> which allowed Kafka connect to mount a volume, and we will use this data for Kafka connector (3).</p><p><a href="https://strimzi.io/blog/2021/07/22/using-kubernetes-config-provider-to-load-data-from-secrets-and-config-maps/">https://strimzi.io/blog/2021/07/22/using-kubernetes-config-provider-to-load-data-from-secrets-and-config-maps/</a></p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaConnect<br>metadata:<br>  namespace: kafka<br>  name: kafka-connect-mssql-2019-source-cluster<br>  annotations:<br>    strimzi.io/use-connector-resources: &quot;true&quot;<br>spec:<br>  image: &quot;asia.gcr.io/kafka-lab/kafka-connect-mssql2019:1.0.0&quot;<br>  version: 3.2.3<br>  replicas: 1<br>  bootstrapServers: &quot;cluster-kafka-bootstrap:9093&quot;<br>  tls: # &lt;- Set CA cluster certificate (1)<br>    trustedCertificates:<br>      - secretName: &quot;cluster-cluster-ca-cert&quot;<br>        certificate: ca.crt<br>  authentication: # &lt;- Set user certificate (2)<br>    type: tls<br>    certificateAndKey:<br>      secretName: user<br>      certificate: user.crt<br>      key: user.key<br>  externalConfiguration: # &lt;- Set monunt volume from kafka connector certificate (3)<br>    volumes:<br>      - name: kafka-user-auth-tls<br>        secret:<br>          secretName: user-auth-tls<br>  config:<br>    config.providers: directory,secrets<br>    config.providers.directory.class: org.apache.kafka.common.config.provider.DirectoryConfigProvider<br>    config.providers.secrets.class: io.strimzi.kafka.KubernetesSecretConfigProvider<br>    config.storage.replication.factor: 3<br>    config.storage.topic: ms-source-connect-cluster-configs<br>    group.id: ms-source-connect-cluster<br>    key.converter.schemas.enable: false<br>    offset.storage.replication.factor: 3<br>    offset.storage.topic: ms-source-connect-cluster-offsets<br>    status.storage.replication.factor: 3<br>    status.storage.topic: ms-source-connect-cluster-status<br>    value.converter.schemas.enable: false</pre><p>After that, we also need to configure the Kafka connector, since Kafka Connect is just a task manager, but the item that actually processes the task is the connector. In this article, we use Debezium as our plugin to pull data from a source database into Kafka’s broker. You may think this part does not require configuring a TLS, but it does. Due to the fact that Debezium needs to create a topic inside Kafka for task history.</p><p>Furthermore, to configure Kafka connector to communicate with Kafka cluster, you need to set a “keystore” and “truststore” path and its password <strong>(1),</strong> which is the same as Kafka UI. That’s why we mount a secret in the volume.</p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaConnector<br>metadata:<br>  namespace: kafka<br>  name: source-sql-server-connector<br>  labels:<br>    strimzi.io/cluster: kafka-connect-mssql-2019-source-cluster<br>spec:<br>  class: io.debezium.connector.sqlserver.SqlServerConnector<br>  tasksMax: 1<br>  config:<br>    connector.class: io.debezium.connector.sqlserver.SqlServerConnector<br>    database.dbname: animal<br>    database.encrypt: true<br>    database.history.kafka.topic: booboo.history.random-topic<br>    database.hostname: 10.242.128.3<br>    database.password: 123qweasdzxc<br>    database.port: 1433<br>    database.server.name: cloudSQL<br>    database.ssl: true<br>    database.trustServerCertificate: true<br>    database.user: sqlserver<br>    errors.deadletterqueue.topic.name: cdc_random-topic<br>    errors.tolerance: all<br>    key.converter.schemas.enable: false<br>    offset.flush.interval.ms: 15000<br>    poll.interval.ms: 1000<br>    snapshot.mode: initial<br>    table.include.list: dbo.random<br>    topic: cloudSQL.dbo.random<br>    value.converter.schemas.enable: false<br>    # TLS configuration (1)<br>    database.history.kafka.bootstrap.servers: &quot;cluster-kafka-bootstrap:9093&quot;<br>    database.history.producer.security.protocol: SSL<br>    database.history.producer.ssl.keystore.location: /opt/kafka/external-configuration/kafka-user-auth-tls/keystore.p12<br>    database.history.producer.ssl.keystore.password: 123qweasdzxc<br>    database.history.producer.ssl.truststore.location: /opt/kafka/external-configuration/kafka-user-auth-tls/truststore.jks<br>    database.history.producer.ssl.truststore.password: 123qweasdzxc<br>    database.history.consumer.security.protocol: SSL<br>    database.history.consumer.ssl.keystore.location: /opt/kafka/external-configuration/kafka-user-auth-tls/keystore.p12<br>    database.history.consumer.ssl.keystore.password: 123qweasdzxc<br>    database.history.consumer.ssl.truststore.location: /opt/kafka/external-configuration/kafka-user-auth-tls/truststore.jks<br>    database.history.consumer.ssl.truststore.password: 123qweasdzxc</pre><h4><strong>2. Sink </strong>connect</h4><p>Like the source, we need to build a custom image for our sink, which can follow the Dockerfile and command below.</p><pre>FROM quay.io/strimzi/kafka:0.33.1-kafka-3.3.1<br>USER root:root<br><br>RUN mkdir -p /opt/kafka/plugins<br>ADD https://github.com/aiven/gcs-connector-for-apache-kafka/releases/download/v0.9.0/aiven-kafka-connect-gcs-0.9.0.tar /opt/kafka/plugins<br>RUN cd /opt/kafka/plugins &amp;&amp; tar -xf aiven-kafka-connect-gcs-0.9.0.tar &amp;&amp; rm -rf aiven-kafka-connect-gcs-0.9.0.tar<br><br>USER 1001</pre><pre>docker build - t asia.gcr.io/kafka-lab/kafka-connect-mssql2019:1.0.0 .</pre><p>Sink connectors, like source connectors, must set a CA (1) and user secret (2) but do not need to mount a certificate volume because they do not need to connect to the cluster.</p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaConnect<br>metadata:<br>  namespace: kafka<br>  name: kafka-connect-mssql-2019-source-cluster<br>  annotations:<br>    strimzi.io/use-connector-resources: &quot;true&quot;<br>spec:<br>  image: &quot;asia.gcr.io/tildi-playground-0001/mle-kafka-connect-mssql2019:v1.0.0&quot;<br>  version: 3.2.3<br>  replicas: 1<br>  bootstrapServers: &quot;cluster-kafka-bootstrap:9093&quot;<br>  tls: # &lt;- Set CA cluster certificate (1)<br>    trustedCertificates:<br>      - secretName: &quot;cluster-cluster-ca-cert&quot;<br>        certificate: ca.crt<br>  authentication: # &lt;- Set user certificate (2)<br>    type: tls<br>    certificateAndKey:<br>      secretName: user<br>      certificate: user.crt<br>      key: user.key<br>  config:<br>    config.storage.replication.factor: 3<br>    config.storage.topic: ms-source-connect-cluster-configs<br>    group.id: ms-source-connect-cluster<br>    key.converter.schemas.enable: false<br>    offset.storage.replication.factor: 3<br>    offset.storage.topic: ms-source-connect-cluster-offsets<br>    status.storage.replication.factor: 3<br>    status.storage.topic: ms-source-connect-cluster-status<br>    value.converter.schemas.enable: false</pre><p>In the sink connector, I set a file name prefix to be “animal/random/,” so when data was inserted into the database, it would transfer here, and then you would need to add the key, which was generated from the GCP service account, which I show early.</p><pre>apiVersion: kafka.strimzi.io/v1beta2<br>kind: KafkaConnector<br>metadata:<br>  namespace: kafka<br>  name: sink-gcs-connector<br>  labels:<br>    strimzi.io/cluster: kafka-connect-gcs-sink-cluster<br>spec:<br>  class: io.aiven.kafka.connect.gcs.GcsSinkConnector<br>  tasksMax: 2<br>  config:<br>    file: /opt/kafka/LICENSE<br>    file.compression.type: gzip<br>    file.name.prefix: animal/random/<br>    file.name.template: &#39;{{timestamp:unit=yyyy}}/{{timestamp:unit=MM}}/{{timestamp:unit=dd}}/{{topic}}-{{partition}}-{{start_offset}}.gz&#39;<br>    format.output.fields: key,value,offset,timestamp<br>    format.output.type: jsonl<br>    gcs.bucket.name: kafka-source-lab<br>    gcs.credentials.json: |<br>      {<br>        &quot;type&quot;: &quot;service_account&quot;,<br>        &quot;project_id&quot;: &quot;kafka-lab&quot;,<br>        &quot;private_key_id&quot;: &quot;&lt;private_key_id&gt;&quot;,<br>        &quot;private_key&quot;: &quot;&lt;private_key&gt;&quot;,<br>        &quot;client_email&quot;: &quot;kafka-lab@kafka-lab.iam.gserviceaccount.com&quot;,<br>        &quot;client_id&quot;: &quot;&lt;client_id&gt;&quot;,<br>        &quot;auth_uri&quot;: &quot;https://accounts.google.com/o/oauth2/auth&quot;,<br>        &quot;token_uri&quot;: &quot;https://oauth2.googleapis.com/token&quot;,<br>        &quot;auth_provider_x509_cert_url&quot;: &quot;https://www.googleapis.com/oauth2/v1/certs&quot;,<br>        &quot;client_x509_cert_url&quot;: &quot;https://www.googleapis.com/robot/v1/metadata/x509/kafka-lab%kafka-lab.iam.gserviceaccount.com&quot;<br>      }<br>    key.converter.schemas.enable: false<br>    tasks.max: 1<br>    topics: cloudSQL.dbo.random<br>    value.converter.schemas.enable: false</pre><p>After several configurations, you can execute the command below to see the result.</p><pre>helm install kafka-cluster kafka-cluster-chart  \<br>--values kafka-cluster-chart/values.yaml \<br>--namespace kafka</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*xS14BmAw834487eC_wI3CA.png" /><figcaption>Helm install</figcaption></figure><p>However, you will get some errors since it’s an error from being unable to find the certificate that you need to generate manually, as I mentioned earlier. After you generate a certificate, the error will disappear, and you can check the result from the Kafka UI and GCS bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZYHSaNtAgl-IYiGQfEIFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyAoWpvRIvJ2nath9Hd37Q.png" /><figcaption>First time install cluster (left), After generate client certificate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJnxxzd-66R3CGsB0fnjEQ.png" /><figcaption>Result in GCS bucket</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpG3Z1yc9-j-iLxiOeYfcQ.png" /><figcaption>Result in Kafka UI</figcaption></figure><h3>How to config Schema Registry to have secure connection ?</h3><p>Next, configure the schema registry to support TLS connections. The method will be the same as Kafka’s UI: mount secret into the volume <strong>(1)</strong>, and then mount a secret file into container <strong>(2)</strong>. Last, we configure the trust store, key store, and its password <strong>(3)</strong>.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: release-name-cp-schema-registry<br>  labels:<br>    app: cp-schema-registry<br>    chart: cp-schema-registry-0.1.0<br>    release: schema-registry<br>    heritage: Helm<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: cp-schema-registry<br>      release: schema-registry<br>  template:<br>    metadata:<br>      labels:<br>        app: cp-schema-registry<br>        release: schema-registry<br>      annotations:<br>        prometheus.io/scrape: &quot;true&quot;<br>        prometheus.io/port: &quot;5556&quot;<br>    spec:<br>      securityContext:<br>        fsGroup: 10001<br>        runAsGroup: 10001<br>        runAsNonRoot: true<br>        runAsUser: 10001<br>      volumes: # &lt;- Mount volume with secret (1)<br>        - name: kafka-user-auth-tls<br>          secret:<br>            secretName: user-auth-tls<br>        - name: jmx-config<br>          configMap:<br>            name: release-name-cp-schema-registry-jmx-configmap<br>      containers:<br>        - name: prometheus-jmx-exporter<br>          image: &quot;solsson/kafka-prometheus-jmx-exporter@sha256:6f82e2b0464f50da8104acd7363fb9b995001ddff77d248379f8788e78946143&quot;<br>          imagePullPolicy: &quot;IfNotPresent&quot;<br>          command:<br>          - java<br>          - -XX:+UnlockExperimentalVMOptions<br>          - -XX:+UseCGroupMemoryLimitForHeap<br>          - -XX:MaxRAMFraction=1<br>          - -XshowSettings:vm<br>          - -jar<br>          - jmx_prometheus_httpserver.jar<br>          - &quot;5556&quot;<br>          - /etc/jmx-schema-registry/jmx-schema-registry-prometheus.yml<br>          ports:<br>          - containerPort: 5556<br>          resources:<br>            {}<br>          volumeMounts:<br>          - name: jmx-config<br>            mountPath: /etc/jmx-schema-registry<br>        - name: cp-schema-registry-server<br>          image: &quot;confluentinc/cp-schema-registry:6.2.0&quot;<br>          imagePullPolicy: &quot;IfNotPresent&quot;<br>          volumeMounts: # &lt;- Mount volume with container (2)<br>            - name: kafka-user-auth-tls<br>              mountPath: /etc/schema-registry/secrets<br>              readOnly: true<br>          ports:<br>            - name: schema-registry<br>              containerPort: 8081<br>              protocol: TCP<br>            - containerPort: 5555<br>              name: jmx<br>          resources:<br>            {}<br>          env:<br>          - name: SCHEMA_REGISTRY_HOST_NAME<br>            valueFrom:<br>              fieldRef:<br>                fieldPath: status.podIP<br>          - name: SCHEMA_REGISTRY_LISTENERS<br>            value: http://0.0.0.0:8081<br>          # Config TLS (3)<br>          - name: SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS<br>            value: cluster-kafka-bootstrap:9093<br>          - name: SCHEMA_REGISTRY_KAFKASTORE_SSL_TRUSTSTORE_PASSWORD<br>            valueFrom:<br>              secretKeyRef:<br>                name: user-auth-tls<br>                key: password<br>                optional: false<br>          - name: SCHEMA_REGISTRY_KAFKASTORE_SSL_KEYSTORE_PASSWORD<br>            valueFrom:<br>              secretKeyRef:<br>                name: user-auth-tls<br>                key: password<br>                optional: false<br>          - name: SCHEMA_REGISTRY_KAFKASTORE_SSL_KEY_PASSWORD<br>            valueFrom:<br>              secretKeyRef:<br>                name: user-auth-tls<br>                key: password<br>                optional: false<br>          - name: SCHEMA_REGISTRY_KAFKASTORE_SECURITY_PROTOCOL<br>            value: &quot;SSL&quot;<br>          - name: SCHEMA_REGISTRY_KAFKASTORE_SSL_KEYSTORE_LOCATION<br>            value: &quot;/etc/schema-registry/secrets/keystore.p12&quot;<br>          - name: SCHEMA_REGISTRY_KAFKASTORE_SSL_TRUSTSTORE_LOCATION<br>            value: &quot;/etc/schema-registry/secrets/truststore.jks&quot;<br>          - name: SCHEMA_REGISTRY_SSL_KEYSTORE_TYPE<br>            value: &quot;PKCS12&quot;<br>          - name: SCHEMA_REGISTRY_SSL_TRUSTSTORE_TYPE<br>            value: &quot;JKS&quot;<br>          # Config TLS<br>          - name: SCHEMA_REGISTRY_KAFKASTORE_GROUP_ID<br>            value: release-name<br>          - name: SCHEMA_REGISTRY_MASTER_ELIGIBILITY<br>            value: &quot;true&quot;<br>          - name: SCHEMA_REGISTRY_HEAP_OPTS<br>            value: &quot;-Xms512M -Xmx512M&quot;<br>          - name: JMX_PORT<br>            value: &quot;5555&quot;</pre><h3>Summary</h3><p>Right now, we can set up our broker to have a secure connection, which provides better security for our connection. However, this article does not explain how to precisely gain permission or an ACL, which I highly recommend reading in <a href="https://www.systemcraftsman.com/2020/09/30/simple-acl-authorization-on-strimzi-using-strimzi-kafka-cli/"><strong>this blog</strong></a><strong>. </strong>Moreover, the example that I show about Kafka Connect depends on third-party configuration, so if your project uses another third party, you should read the document carefully, but in my opinion, the way to configure it will be similar.</p><h3>Reference</h3><ul><li><a href="https://strimzi.io/docs/operators/latest/configuring.html">Configuring Strimzi (0.33.2)</a></li><li><a href="https://debezium.io/documentation/reference/stable/connectors/mysql.html">Debezium connector for MySQL</a></li></ul><p><a href="https://strimzi.io/blog/2021/07/22/using-kubernetes-config-provider-to-load-data-from-secrets-and-config-maps/">https://strimzi.io/blog/2021/07/22/using-kubernetes-config-provider-to-load-data-from-secrets-and-config-maps/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b73cfc4aea1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cj-express-tech-tildi/lets-secure-our-kafka-component-in-the-kafka-cluster-with-tls-8b73cfc4aea1">Let’s secure our Kafka component in the Kafka cluster with TLS!</a> was originally published in <a href="https://medium.com/cj-express-tech-tildi">CJ Express Tech (TILDI)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello Transformer and Goodbye CNN ?]]></title>
            <link>https://medium.com/@RTae/hello-transformer-and-goodbye-cnn-4ebda6e4aa5e?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ebda6e4aa5e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 09:52:12 GMT</pubDate>
            <atom:updated>2021-07-27T09:54:28.695Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hello Transformer and Goodbye CNN ?</h3><p>สวัสดีครับ ผมเต้ วันนี้ผมอยากมาแชร์อะไรหน่อยเกียวกับโลกของ Computer Vision ช่วงนี้ฝึกงานที่ Dynamic Intelligence Asia (DIA) เลยได้ Research เรื่อง Computer Vision เยอะมาก และ ผมได้ไป Research เรื่อง Transformer กับ Computer Vision แล้วรู้สึกอินมากๆ กับ ความพ่อทุกสบานบันของ Transformer จึงมาแชร์ว่า Transformer ที่อยู่ใน Computer Vision มันดีกว่า Convolutional Neural Network (CNN) ยังไง แล้วมันมาแทน CNN เลยรึปร่าว โดยเนื้อหาทั้งหมดจะมาจาก Paper <a href="https://arxiv.org/pdf/2010.11929.pdf"><strong>“AN IMAGE IS WORTH 16X16 WORDS: TRANSFORMERS FOR IMAGE RECOGNITION AT SCALE”</strong></a> หรือ ที่เรียกกันว่า Vision Transformer (ViT)</p><p>โดยประเด่นที่ผมอยากมาเหล่าให้ฟังมีดังนี้</p><ul><li><strong>What is Vision Transformer ?</strong></li><li><strong>How Vision Transformer work ?</strong></li><li><strong>Why Transformer in Computer Vision is better than CNN ?</strong></li><li><strong>Can Transformer replace CNN ?</strong></li><li><strong>Conclusion</strong></li></ul><h3>What is Vision Transformer ?</h3><p>ก่อนแรกเรามารู้จัก Transformer กันแบบคร่าวๆ ว่ามันคืออะไร เดิมที่ Transformer นั้นเริ่มมาจากวงการของ NLP โดยมาจาก Paper ที่ชื่อว่า <a href="https://arxiv.org/pdf/1706.03762.pdf"><strong>“Attention Is All You Need”</strong></a><strong> </strong>ซึ่งเรียกได้ว่า Model DL พวก LSTM หลายตัวๆ ถึงกับตกกระป๋องไปเลย เพราะ ด้วยนำเสนอสถาปัตยกรรม Transformer ที่ใช้ self-attention มาดึง Feature ทำให้ได้ Accuracy ที่ดีขึ้นมาก บวกกับ Resource ในการ Computation ก็ต่ำลงไปด้วย จึงทำให้ Transformer นิยมมากขึ้น จนเกิด Model NLP ดังๆ อย่าง BERT ที่ถ้าใครอยู่ในวงการ NLP ก็อ๋อกันทุกคน แล้ว Transformer มันมาอยู่ใน Computer Vision ได้ยังไงละ ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K466SzWt8CtjnsBUQVw04g.png" /><figcaption>Figure 1 DETR Architecture <a href="https://arxiv.org/pdf/2005.12872.pdf">Source</a></figcaption></figure><p>ในปี 2019 Facebook ได้ Publish Paper นึงชื่อว่า <a href="https://arxiv.org/pdf/2005.12872.pdf"><strong>“End-to-End Object Detection with Transformers”</strong></a><strong> </strong>ที่เป็นการทำ CNN มาใช้กับ Transformer โดยใช้ CNN ในการ Extract Feature แล้วค่อย Feed Featureให้ Transformer ต่อเพื่อทำ Object Detection โดยอ้างอิงจาก <strong>Figure 1</strong> ซึ่งถือเป็นก้าวหนึ่งที่ดีของการนำ Transformer มาใช้ในการ Computer Vision</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*BatqCsBcsiukvybyPnKxog.png" /><figcaption>Figure 2 ViT Architecture <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a></figcaption></figure><p>ซึ่งมาในปี 2020 Google ได้แสดงพลังแห่ง Transformer อีกครั้ง โดยการปล่อย Paper <a href="https://arxiv.org/pdf/2010.11929.pdf"><strong>“AN IMAGE IS WORTH 16X16 WORDS: TRANSFORMERS FOR IMAGE RECOGNITION AT SCALE”</strong></a><strong> </strong>โดยได้เสอน Architecture ชื่อ Vision Transformer ในการแก้ไขปัญหา Image classification ที่อยู่ใน Computer vision โดยไม่มีการใช้ <strong>Convolutional Neural Network (CNN) </strong>แม้แต่กระบวนการเดียว ถื่อเป็น End to End Transformer เลย ซึ่งหลังจากปล่อย Paper นี้ออกมาได้กลายเป็น State of the art (SOTA) ทันทีในหมวด Image classification ( ไม่แน่ใจตอนนี้โดน Paper อะไรมาแทนยัง เพราะ Paper นี้ Publish มาหลายเดือนแล้ว ) โดย ViT ได้เลือกใช้ Transformer Encoder ในการ Extract feature ออกมาเพียงอย่างเดียว ซึ่งสำหรับผมถือว่าว้าว มากๆ เพราะ การใช้ CNN ใน Computer Vision ถือเป็นเรื่องที่ตายตัวมาก แต่ Paper ได้ทำให้โลก Computer Vision แปลกใหม่มาทันที</p><h3>How Vision Transformer work ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6JJsyEU5Hns3lo_Cx3SLg.jpeg" /><figcaption>Figure 3 ViT Architecture and label</figcaption></figure><p>แล้ว ViT นี้มันทำงานยังไงละ โดยผมจะอิงจาก <strong>Figure 3</strong> ที่มี label บอก Step การทำงานอยู่</p><h4><strong>1) Split an image into patches</strong></h4><p>โดยในขั้นแรก ต้องเริ่มจากการแบ่งภาพทีใส่เข้ามา ออกเป็น Patche ก่อน โดยสาเหตุที่ต้องแบ่งรูปภาพ ออกมาเป็น Patche เพราะ Paper มีหลักการออกแบบมาจาก Model อย่าง BERT จึงจะใช้ Concept ที่นำ Word แต่ละ Word เข้าไปใน Tranfromer ดังนั้น Architecture ViT จะทำการเปลี่ยนรูปภาพใหญ่ ให้เป็น Patche ย่อยๆ เหมือนกับ Word คำ เป็นแบบ Sequence tokens แล้วค่อย Feed เข้า Tranfromer ต่อไป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJYvCYur67Q3amFEn5rjUA.jpeg" /><figcaption>Figure 4 Home as a patches 16 x 16</figcaption></figure><p>โดยถ้าเราลองนำรูปขนาด 224 x 224 แล้วแบ่งให้ได้ขนาด Patche 14 x 14 เราจะได้รูปที่แบ่งออกมาเป็น Patched ย่อยๆ 16 x 16 ตาม <strong>Figure 4 </strong>ก็จะเป็นที่มาของ ชื่อ Paper นี้ และ จะเห็นได้ว่ามันไม่เหมือนกับ <strong>Figure 3</strong> เพราะ Paper แค่ยกตัวอย่างเฉยๆ และ ขนาดของ Patche สามารถปรับเปลี่ยนได้ โดยถ้าอ้างอิงจาก Paper ยิ่งขนาด Patche เล็กลงก็ต้องใช้ Resource ที่ Train มากขึ้น และ ให้ง่ายต่อการนำเสอนผมจะขอ Split Patche ให้เป็นแบบ 3 x 3 ก็จะได้ตาม <strong>Figure 5</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fkr8pMSM6LCyCqI4Y0YkMQ.jpeg" /><figcaption>Figure 5 Home as a patches 3 x 3</figcaption></figure><h4>2) Flatten the patches and embed flatten patches to lower dimension</h4><p>หลักจากที่ทำการแบ่งรูปภาพของเป็น Patche ย่อยๆ แล้วเราต้องทำการเปลี่ยนจาก Tensor ขนาด d x d x 3 ให้กลายเป็น Vector ขนาด d*d*3 x 1 โดยที่ d คือ ขนาดของ Patche และ ต้องทำการ Embed vector เพื่อให้ขนาดของ Vector เหมาะสมสำหรับ Feed เข้า Tranfromer ได้ โดนทั่วไปการ Embed vector เราก็จะใช้ Dense layer เพื่อให้ได้ Vector ที่เราต้องการ ก็จะทำให้ได้ผลลัพธ์เหมือน <strong>Figure 6</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpc78YwEbDpfSb-9KdzULg.jpeg" /><figcaption>Figure 6 Home become vector</figcaption></figure><h4>3) Add positional embeddings</h4><p>หลักจากที่มีการ Embedded Vector แล้ว เพื่อให้สามารถ Feed เข้า Tranfomer ได้ก่อนหน้านั้น ก็ต้องมีการทำ Positional embedding ก่อน แล้วมันคืออะไรละ เนื่องจากตัว Transformer ที่จะใช้ใน Paper ViT เป็น Transformer Encoder ซึ่งภายในนั้นจะมี Muti-head self attention ที่เป็น attention ที่สามารถ Share parameter กันได้ในแต่ละ Token ที่ Feed เข้าไปในกรณีนี้คือ Patche ที่มาจากการแบ่งของรูปใหญ่ เพื่อป้องกันใม่ให้ ภาพมันสลับต่ำแหน่งกันมั่วชั่ว เหมือนใน NLP ลำดับของคำนั้นก็มีความหมาย เลยต้องมีการทำ Positional embedding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qYJmwA17AWfml9WDANJ_w.jpeg" /><figcaption>Figure 7 Home when not label with Position embeddings</figcaption></figure><p>ถ้าบางคนยังไม่เห็นภาพ ให้ดู <strong>Figure 7</strong> ลองดูภาพ ซ้ายกับขวาเทียบกัน สำหรับคน และ Transformer นั้น 2 ภาพนี้แตกต่างกันสินเชิง แทบจะไม่รู้เลยว่ามันคือ แมว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7SDaG_L5RZMorl02rT6lA.jpeg" /><figcaption>Figure 8 Home when label with Position embeddings</figcaption></figure><p>แต่เอามาใหม่ ถ้าเราทำการ Positional embedding เหมือนกับการ Label แต่ละ Patche ควรอยู่ตำแหน่ง ให้ดูที่เลขที่อยู่บนรูปภาพจะเป็นตัวบอกตำแหน่งของรูปภาพ โดยไล่จาก ซ้ายไปขวาบนลงล่าง (1–9) สำหรับคนก็อาจจะไม่รู้เรื่องเหมือนเดิม 5555 แต่ Transformer นั้นสองภาพนี้ คือภาพเดียวกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQd7QCAlvUXmr-1EZoChYQ.png" /><figcaption>Figure 9 Positional embedding experiment <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a></figcaption></figure><p>ซึ่งใน Paper นี้ก็มีการทำ Positional embedding หลากหลายรูปแบบ แต่เอาง่ายๆสุดก็คือ เหมือนมี Lookup table และก็ยิบ Label มาบวกกับ Patche เลย แต่ที่น่าสนใจคือ ผลลัพธ์ที่ได้จากการทดลองนี้ คือ Positional embedding จะมี หรือ ไม่มี หรือ ใช้วิธีในก็ตามก็ไม่ได้ผลลัพธ์ที่แตกต่างกันมากซึ่งน่าสนใจมากๆ แปลว่า Transformer ไม่ได้สนใจความสัมพันธ์ของลำดับ ของ Pacthe แต่จะไปสนใจว่า แต่ละ Pacthe มีความเชื่มโยงกันได้อย่างไร</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*SICaK34SV-_GynxhPaqfgg.png" /><figcaption>Figure 10 Positional embedding when train <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a></figcaption></figure><p>ซึ่งใน Paper นี้ก็ได้มีการใช้ Positional embedding ที่สามารถ Train ได้ซึ่งก็เจ็งดีที่ได้เห็นว่า Positional embedding สามารถ Represent ตำแหน่งของตัวเองได้ดีมากจาก <strong>Figure 10</strong></p><p><strong>4) Add Class token for classification</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ina5qOuFGcS9RaEsP-adlw.jpeg" /><figcaption>Figure 11 Positional embedding when train</figcaption></figure><p>เพื่อที่จะสามารถ Predict Class ออกมาได้ต้องมีการใส่ Class token หรือ Cls token มันคือ Vector ที่เท่ากับจำนวนของ Class ที่เราต้องการ Predict ว่ามันคือ อะไร โดยก็ ทำการเอากับบวกกับ Positional embedding แล้วเอาไปใส่ใน Transformer พร้อมกับ Patche ของรูปภาพ</p><h4>5) Feed the sequence as an input to standard transformer encoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*qRqCGhgmtzraZY6SC5hqxQ.png" /><figcaption>Figure 12 Transformer Encoder <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a></figcaption></figure><p>ในขั้นตอนต่อมาเป็นการนำ Patche และ Cls ไป Feed เข้า Transformer encoder ตามปกติเลย โดยผมไม่อยากลงรายละเอียดของ Transformer มาก เพราะ เนื่อหาค่อนข้างเยอะ สามารถเขียนเป็น Blog ใหม่ได้เลย แต่ถ้าใครสนใจก็สามารถลองอ่านได้จาก <a href="https://arxiv.org/pdf/1706.03762.pdf">“<strong>Attention Is All You Need</strong>”</a> ได้เลย แต่ให้สรุปง่ายๆ ในขั้นตอนนี้ก็คือเอาทุกอยากที่เราเตียมมาเอาไป Concatenate กันแล้ว feed เข้า Transformer encoder แค่นั้น เพราะ จากท่ีกล่าวไปข้างใน Transformer encoder จะมี Multi-Head Attention ที่จะ Share parameter กันจะทำให้ Transformer เห็นทุก Patche</p><p><strong>6) Classify it</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKElva-izcVhG9h74QWAxg.jpeg" /><figcaption>Figure 13 MLP + Softmax Head to get the predict result</figcaption></figure><p>หลังจาก Feed เข้า Transformer encoder แล้ว ก็ทำการดึงไปเข้าพวก MLP Network จะทำ Dense Layer กี่ชั้นก็ว่า แล้วก็จบด้วย Softmax แต่จะเห็นได้ว่าเราไม่จำเป็นต้องดึงทุก Token ( Patche + Cls token ) ออกมาเพื่อทำการ Predict เพราะ ข้างใน Transformer encoder จะมี Multi-Head Attention ที่จะ Share parameter กัน เพียงแค่ดึง Token แรก ที่เป็น Cls token มาใช้ก็พอแล้ว</p><p>สุดท้ายนี้เราก็จะสามารถทำ Image Classification แบบใช้ Transformer แบบ end to end ได้แล้ว โดยผมก็ได้มีรูปสรุปเป็น Gif เพื่อ Visualize ให้เข้าใจมากขึ้นด้วย ดัง <strong>Figure 14</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_c8SqxPMY_dsApyvDJ8HtA.gif" /><figcaption>Figure 14 Visualize ViT Architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9j0ZfOaPe97VTBS4Jeb6w.png" /><figcaption>Figure 15 ViT Architecture type <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZbSYYfXLh-7WDGe7eY0Mw.png" /><figcaption>Figure 16 ViT Architecture type <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a></figcaption></figure><p>โดยสรุปแล้วการอธิบายของผมนั้นเป็นการยกตัวอย่างของหลักการทำงานของ ViT แต่ผมยังไม่ได้พูดพึงสมมการข้างใน เช่น สมการของ Multihead Self-Attention ที่เป็นส่วนสำคัญใน Paper นี้มาก และ ยังร่วมไปถึงรายละเอียดของ Positional embedding ซึ่งถ้ามีโอกาศผมจะมาเขียนให้อ่านกัน อีกทั่งพวกเลขที่ผมยกตัวอย่างจะไม่ใช้ Official จาก Paper ผมแค่ยกตัวอย่างเพื่อความง่ายในการนำเสอน แต่ตัว Official นั้นจะสามารถดูได้จาก <strong>Figure 15 </strong>และ <strong>Figure 16 </strong>ที่มีทั้ง Type ของ Architecture และ ขนาดของ Patche ที่แตกต่างกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*rbNtY43YuVwXuQYcVFDN6w.png" /><figcaption>Figure 17 Attention Visualize <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a></figcaption></figure><p><strong>Figure 17 </strong>จะแสดงให้เห็นว่า Attention ใน Transformer มีการ สั่งเกตุภาพนั้นได้อย่างไรบาง ซึ่งบางคนก็อาจคุ้นเคยกันดีใน CNN ถ้า Plot ออกมาเป็น Gradient แบบ Heat-map ก็จะได้ภาพประมาณนี้ ก็จะเห็นได้ว่า Transformer พยามจะไม่สนใจ Background แต่จะไป Focus ที่รูปที่ต้องการ Classify ซึ่งถือว่าทำได้ดีมาก</p><h3>Why Transformer in computer vision is better than CNN ?</h3><p>ตอนนี้ทุกคนอ้างสงสัยแล้วว่า Transformer มันดีกว่า CNN ยังไง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrtAQ8QHtpGNxWoVOsQx6w.png" /><figcaption>Figure 18 Left: ViT Mean attention distance <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a> Right: CNN Receptive field Growth</figcaption></figure><p>ในข้อที่โดดเด่นชัดเจนเลยของการนำ Transformer มาแทน CNN คือจาก <strong>Figure 18 </strong>สองกราฟนี้ได้แสดง ความสามารถในการ learned non-local interactions pixel ของ Transformer และ CNN จากรูปซ้ายจะสามารถสังเกตุได้ว่า <strong>แค่เพียง Layer แรก จะมีบาง Head ที่อยู่ใน Transformer (Attention Head) สามารถเรียนรู้ Pixel ที่ห่างออกไปได้แล้ว</strong> โดยไม่ต้องโดน Limit ที่ Local Pixel หรือ ก็คือสามารถมองภาพได้กว้างมากขึ้น ไม่เหมือนกับ CNN ที่ต้องทำให้ Layer Complex มากขึ้นเรื่อยๆ จึงสามารถมองภาพได้กว้างมากขึ้น ดังรูปขวา ถ้าลองดูเทียบกันแล้วนี้คือ หมากสำคัญที่ทำให้ Transformer เหนือกว่าโดนไม่มีข้อกังขา ถ้าเทียบกันแบบง่ายๆ ความสามารถในการเรียนของ Transformer โตแบบ Expo (ซึ่งก็อาจไม่จำเป็น เพราะ แค่ Layer แรก็เรียนได้แล้ว) แต่ CNN จะค่อยๆ โตแบบ Linear ซึ่งจะเป็นสาเหตุว่าทำมัย Transformer จึงใช้ Resource น้อยกว่าอ้างอิงจาก <strong>Figure 16 </strong>ที่จะใช้ TPU core น้อยกว่าประมาณ 3 เท่าเหมือนเทียบกับ<strong> </strong>Transformer ตัวที่ใหญ่ที่ในกราฟ กับ CNN (ViT-H/14 and BiT-L) ( เอาเขาจริงๆ มันก็มุกตลกร้ายนะ เล่นใช้ TPU ที่จริงๆ ตอนนี้มีแค่ Google ที่มีอยู่คนเดียวบนโลกนี้ 5555 แทบ Dataset นี้ก็ไม่ธรรมดา JFT Dataset ที่เป็น Private ของ Google เพียงคนเดียว)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*KyYzlJTw1rZwQx03t-DDbQ.png" /><figcaption>Figure 19 First 28 component of transformer <a href="https://arxiv.org/pdf/2010.11929.pdf">Source</a></figcaption></figure><p>Computer vision Network ที่ดีควรมี Kernel ที่ Smooth ที่สามาแยกแยะความแตกต่างของ Pixel ได้ดี จะเห็นว่า Transformer ใน ViT แค่ Layer แรกๆ ก็มี Kernel ที่ Smooth แล้ว</p><h3>Can Transformer replace CNN ?</h3><p>พูดมาซะขนาดนี้ Transformer จะมาแทน CNN เลยหรอคำตอบคือ <strong>ไม่ครับ แต่อนาคตไม่แน่ </strong>แล้วเพราะอะไรละ Factor นึงที่ผมอยากมองคือ การนำมาขึ้น Production มากกว่าที่จะเป็น SOTA ถึงแม้ Transformer จะได้เป็น SOTA แต่ถ้าเทียบกันที่ตัว Accuracy แล้วมันคือระดับ 1 – 3 % ซึ่งถ้ามาเทียบกับที่ระดับ Production ใหญ่ๆแล้วแทบจะไม่เห็นข้อแตกกต่าง การที่ผมมาฝึกงานที่ DIA ทำให้ผมรู้อย่างนึงก็คือ ถ้า Model มันจะดีขนาดไหน, SOTA , ใหม่ล่ำยุค และ สามารถ Implement ได้จริง แต่เอามาทำ Production ไม่ได้ก็จบเท่านั้น</p><p>ก็จริงที่ Transformer นั้นมีการกิน Resouce ที่น้อยลงแต่… อย่าลืมนะครับ Paper นี้ใช้ TPU!! ซึ่งราคาต่างกันลิบลับกับ GPU T4 ใน colab ที่เราใช้กันเลย ในความจริงนั้น เราต้องการ model ที่ Inference speed ค่อนข้างสูงและ Accuracy พอใช้ได้ และ ยิ่งถ้า Product ตัวนั้นต้องเจอ Load สูงๆ ทำให้เป็นเรื่องที่สำคัญมาก ดังนั้นการ Optimize model ก็เป็นอีกเรื่องที่ควรคำนึงถ้าต้องการเอา ซึ่งถ้าเอา TPU มา Inference Cost คงบานปลาย มหาศาล ซึ่งถ้าในอนาคต มี Transformer แบบใหม่ที่อยู่ใน Computer vision และ สามารถทำ Inference speed ได้ดีนี้ถือเป็น จุดพลิกของ Transformer เลยที่จะก้าวข้าม CNN</p><p>โดยตัวผมนั้นก็ได้ทำพวก Project ที่ต้องใช้ Object detection ก็ได้ไปเจออีก Paper นึ่งชื่อ <a href="https://arxiv.org/pdf/2103.14030.pdf">“Swin Transformer: Hierarchical Vision Transformer using Shifted Windows”</a> ที่พึงออกต้นปี 2021 ซึ่งเป็นการนำ Transformer มาทำ Object detection โดยใช้ Shifted Windows มาช่วย ซึ่งก็เจ้งมากๆ สำหรับผม</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAuxrbcKuaF_X4rPIiu07g.jpeg" /><figcaption>Figure 20 AP and inference speed comparison <a href="https://www.google.co.th/url?sa=i&amp;url=https%3A%2F%2Ftwitter.com%2Falexeyab84%2Fstatus%2F1380699160748421121&amp;psig=AOvVaw03PkppohRAMThEkfXG0Gb6&amp;ust=1627404790615000&amp;source=images&amp;cd=vfe&amp;ved=0CAkQjhxqFwoTCKig2rWZgfICFQAAAAAdAAAAABAD">source</a></figcaption></figure><p>แต่ก็ไม่นานคนที่เขียน Scaled-YOLOv4 ได้ Publish Paper ห่างกันไม่กี่เดือน ชื่อ <a href="https://arxiv.org/pdf/2105.04206.pdf"><strong>“You Only Learn One Representation: Unified Network for Multiple Tasks (YOLOR)” </strong></a>ได้ตบ SwinT ออกจากบันลัง SOTA ทั้งในแง่ของ AP กับ Inference Speed อย่างรวดเร็ว จาก<strong> Figure 20</strong> ก็จะเห็นว่า Transformer อาจจะยังไม่เห็น Best choice ในการขึ้น Production (ตอนนี้ได้ข่าวว่าคนเขียน YOLOR กำลังทำ YOLO V. Transformer อยู่ก็ลุ้นอยู่ว่าจะเป็นยังไง )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IivrPqa-2DnYu05gDUtruQ.jpeg" /><figcaption>Figure 21 ONNX TensorRT <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.edge-ai-vision.com%2F2020%2F04%2Fspeeding-up-deep-learning-inference-using-tensorflow-onnx-and-tensorrt%2F&amp;psig=AOvVaw1STIHNrhoZ5zqXDxrnTefl&amp;ust=1627405327334000&amp;source=images&amp;cd=vfe&amp;ved=0CAkQjhxqFwoTCMiS1LabgfICFQAAAAAdAAAAABAD">source</a></figcaption></figure><p>ซึ่งตัวผมนั้นปกติก็ไม่เอา Model จาก TF, Pytorch ไปขึ้น Production หรอกแต่มีการ Convert ให้กลายเป็น TensorRT ก่อนจึงนำไปเขียน Logic ต่อไป ในกรณีของ YOLOR ก็ไม่มีปัญหาสามารถเพิ่ม Inference speed ได้ถึง 4 เท่าทำให้ GPU ราคา 5000 บาท สามารถวิ่งได้ที่ 15–18 FPS แต่สำหรับพวก Transformer นี้ยังไม่ง่ายเลย ผมลองเอา ViT แปลงเป็น ONNX แต่กับได้ Inference speed ที่น้อยลง อาจจะมาจาก โครงสร้างของ Transformer ที่ซับซ้อนมากกว่า CNN จึงยากที่จะแปลงให้เป็น Graph ซึ่งก็ต้องรอทาง TensorRT กับ ONNX Update เกี่ยวกับเรื่องนี้ ไม่ก็ผมก็ต้องหาวิธีอื่น</p><p>นี้ก็เป็นอีกสาเหตุที่ Transformer ยังไม่สามารแทน CNN ได้ (เดียววันหลังถ้ามีโอกาศผมจะมาสอนการขึ้น Production กับ Computer vision ให้นะครับ ร่วมไปถึงการ Convert เป็น TensorRT)</p><p>FYI. แต่จริงๆ ผมก็เจอ Transformer ที่ทำ Object detection ได้ Inference speed น่าพอใจแต่ AP ค่อนข้างต่ำ ซึ่งคนเขียนยัง เครมเองว่า Paper นี้ไม่ใช้ High performance object detection แต่ Paper น่าสนใจดี เพื่อใครสนใจอ่าน <a href="https://arxiv.org/pdf/2106.00666.pdf"><strong>“You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection”</strong></a></p><h3>Conclusion</h3><p>ในปีนี้สำหรับการได้มาฝึกงานถือว่าได้เรียนอะไรเยอะมาก ทั้งเรื่องของ Logic bussiness การเอางานไปขึ้น Production และ research model computer vision แบบ Full-time (อยากมานานมากๆๆ แล้ว) ซึ่งการที่ผมได้อ่านเรื่อง Transformer ถือว่าเปิดโลก Computer vision ของผมมาก จาก Paper นี้</p><p>Transformer ได้มาเขย่าวงการ Computer vision ให้เราได้เห็นว่า เขาไม่ได้มีดีแค่ NLP แต่จริงๆ เขาเป็นพ่อทุกสถาบัน ถึงแม้ตอนนี้ จะยังไม่สามารถไปแทน CNN ได้ ซึ่ง ViT สำหรับผมถือเป็นตัวอย่างที่ดีมากของการนำ Transformer ในงาน Computer vision ทำให้เราเห็นในสิ่งที่ไม่เคยมาก่อน เช่นถ้าพูด Computer vision ก็ต้อง CNN แต่ก็ไม่แน่ในอนาคตเราอาจจะเห็น Transformer มาแทน CNN เหมือน LSTM ใน NLP เลยก็ได้ ใครจะไปรู้เมื่อ 20 ปีที่ พวก Classic Computer vision เช่น sift and surf, HOG, BLOB จะโดน CNN แทนในอีก 10 ปี ต่อมา ในตอนนี้ก็อาจมาถึงเวลาของ CNN บางแล้วละที่จะโดน Transformer แทนที่</p><p>อย่างไรก็ตามผมก็หวังว่าจะได้เห็น Transformer ออกมามากขึ้นในงาน Computer vision และ ถ้ามีโอกาศก็อยากร่วม Research งานที่ใช้ Transformer ใน Computer vision ด้วย ขอบคุณครับ</p><p>FYI. แมวในรูปชื่อ Home ไม่ขายแต่ให้ฟรีเลย หยอกๆๆ 55555</p><h4>Reference</h4><p>Attention Is All You Need : <a href="https://arxiv.org/pdf/1706.03762.pdf">https://arxiv.org/pdf/1706.03762.pdf</a></p><p>An Image Is Worth 16X16 Words: Transformers For Image Recognition At Scale : <a href="https://arxiv.org/pdf/2010.11929.pdf">https://arxiv.org/pdf/2010.11929.pdf</a></p><p>End-to-End Object Detection with Transformers : <a href="https://arxiv.org/pdf/2005.12872.pdf">https://arxiv.org/pdf/2005.12872.pdf</a></p><p>Attention Is All You Need, Yannic Kilcher : <a href="https://www.youtube.com/watch?v=iDulhoQ2pro">https://www.youtube.com/watch?v=iDulhoQ2pro</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ebda6e4aa5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Super AI Engineer: Thai MNIST Classification]]></title>
            <link>https://medium.com/@RTae/super-ai-engineer-thai-mnist-classification-facd332fa500?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/facd332fa500</guid>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Sat, 17 Oct 2020 20:26:33 GMT</pubDate>
            <atom:updated>2020-10-19T14:43:37.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*VMz2oNtxS9cF7poAxcJi_A.png" /></figure><p><strong>#22p21c0253-เต้</strong></p><p>สวัสดีครับผมเต้ นักศึกษาปี 3 มหาวิทยาลัยพระจอมเกล้าธนบุรี (KMUTT) วันนี้ผมอยากจะมาเล่าเทคนิคที่ผมใช้ใน Kaggle ของ Super AI Engineer ในสัปดาห์ที่ 5 ในหัวข้อ Thai MNIST Classificaiton ที่ผมได้ใช้ในครั้งนี้ และ โดยส่วนตัวนั้นผมมีความสนใจในหัวข้อ Image มากทำให้สองอาทิตย์ที่ผ่านมาไฟลุกมาก ในการแข่ง</p><h3>Dataset</h3><p>ในก่อนแรกเรามาดู Dataset กันก่อนว่ามันคืออะไร ถ้าพูดคำว่า MNIST บางคนที่เคยทำพวก ML หรือ DL ไม่ว่าจะลงคอร์ส หรือ ลงแข่ง Kaggle ก็คง อ่ออออ ขึ้นมาทันที โดยมันก็คือ Dataset ที่เกี่ยวข้องกับ Handwritten digit ในรูปแบบของตัวเลขอารบิก</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*8ErCkUmr8YmLwB9EAETSrA.png" /><figcaption><a href="https://www.kaggle.com/c/digit-recognizer">https://www.kaggle.com/c/digit-recognizer</a></figcaption></figure><p>แต่ที่นี้ทาง Super AI Engineer ก็เลยมีกลับเขาบ้างเลยได้กลายเป็น Thai MNIST ซึ่งเป็นตัวเลขไทยจากมือคนเขียน โดย Dateset ก็ไม่ได้มาจากไหนมาจากผู้อบรมนี้ละครับ 55555</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*z9Wl837hYTVWflLFhtmHIw.png" /></figure><h3><strong>Problem</strong></h3><p>โดยโจทย์ของ Super AI Engineer ก็คือให้เรา Classification ตัวเลขไทย 0–9 จากลายมือที่เขียนลงกระดาษ Digital เลยได้เป็นไฟล์รูปภาพ แต่โจทย์ยังไม่จบครับ !! ถ้าทำแค่นี้ทาง Super AI Engineer มองว่าแค่นี้อาจง่ายเกินไป ถ้าเราไปเปิดไฟล์ CSV มาอันหนึ่งจะเห็นว่ามี หน้าตาดังรูปข้างล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQu17tQg9OYl6PDKtp32FQ.png" /></figure><p>โดยสิ่งที่เราต้องทำก็คือ ทำ model สร้างความสัมพันธ์ของตัวเลขจาก 3 Feature ที่ให้มา โดยสามารถเป็นได้ตั้งแต่ค่า 0–99 แต่บางคนคงก็แอะ! แล้วไหนตัวเลข มีแต่ไฟล์รูปภาพ ใช่ครับเขาให้ Classification รูปภาพนั้นมาก่อนว่าเป็นตัวเลขอะไร แล้วเอาไปหาความสัมพันธ์ ซึ่งนั้นแปลว่า เราต้องทำ model สองอัน 1. Image Clssification model 2. Regression model ดังนั้น Error ที่เกิดขึ้นจะเป็น Error แบบสะสม</p><h3>Image Classification model</h3><p>ถ้า Image Classification ก็คงหนี้ไม่พ้น Model CNN ที่ให้ประสิทธิภาพได้สูงสุดในถ้าในเรื่องของรูปภาพอยู่แต่ก่อนแรกเรามาดู Dataset แบบ ชัดๆกันก่อน</p><h4>Visualization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7H1Llx00Abu-HRwBvhNnDA.png" /></figure><p>ในส่วนแรกเราจะเห็นได้ว่าข้อมูลที่เป็นตัว Train สำหรับ Image Classfication ไม่ค่อยจะมีปัญหาอะไรแต่อันที่ 2 นะสิมีค่า NaN เดียวเราค่อยไปดูในส่วนถัดไป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W92XVi2AIUxRs-ZCq5NTxQ.png" /></figure><p>แต่พอลองดูขนาดของรูปก็ตกใจนิดๆ ว่าทำไหมถึงเก็บใหญ่ขนาดนี้แต่ก็ไม่เป็นไรเราก็ต้องทำให้ได้อยู่ดี อันนี้ก็เป็นอีกหนึ่งปัญหาที่เราต้องแก้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjKi9GhpBy1jFs6Tbix3cg.png" /></figure><p>พอลองเทียบแต่ละ Class ต่อจำนวน Image ที่มีก็เรียกว่า เกือบจะ Balance (รึปร่าว 5555) แต่สำหรับผมมันไม่ Balance ครับ ดังนั้นนี้ก็เป็นอีกหนึ่งปัญหาที่ต้องแก้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Mut_pc4V7hrSILYFDEbww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IO1RQNq9yt7IXU6gwZ5CKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_8ALog0n0fOIusiLib9eQ.png" /></figure><p>คร่าวนี้มาลองดูตัวเลขกันหน่อยจะเห็นได้ว่า ทั้งความหนา ความบาง ความชัด ขนาด ตำแหน่งการเขียน หรือ แม้กระทั้งรูปแบบ แทบไม่เหมือนกันเลย ค่อนข้างเป็น Dataset ที่อาการหนักมาก ต่างจาก MNIST originโดยผมจะเก็บไว้เป็นปัญหาที่ต้องแก้ไว้ก่อน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNvG9eMQz0yU9WARHBR1pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSEiBRlH0wWAHbUs4qQMCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ejpr-yeObtuecnPKMvWc7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhPmQJmslFQEr1_w1Hebqw.png" /></figure><p>แต่ปัญหามันก็ไม่จบแค่นี้ถ้าเราลองเปิดไฟล์ CSV ไล่ดูแต่ละภาพ ก็จะเห็นได้ว่าบางจะเป็นแบบด้านบนข้างต้น ไม่ก็ label ผิดบ้าง, ไม่รู้ว่ามันคืออะไร ? หรือ ไม่ก็มี เลข 10 ขึ้นมาบาง ซึ่งมันไม่ได้อยู่ใน class หลักของเรา (คนเขียนใจร้ายจัง 55555 ) ซึ่งก็เป็นอีกปัญหาที่ต้องแก้</p><p><strong>สรุปปัญหาตอนนี้</strong></p><ol><li>Size ของภาพใหญ่มาก</li><li>Data imbalance</li><li>รูปภาพค่อนข้างมีความหลากหลายกันสูงมาก ส่วนมากก็มาจากลายมือของผู้เขียน (ไม่ได้ว่านะครับ 5555 ผมก็เขียนแย่เหมือนกัน)</li><li>Noise เยอะมาก ทั้ง Lable ผิด, รูปที่ไม่รู้ว่าคืออะไร และ ไม่มีอยู่ใน Class</li></ol><h4>Prepare data</h4><p>ตอนนี้เราลองมาหาวิธีแก้แต่ละปัญหากันดีกว่า</p><p><strong>1 Size ของภาพที่ใหญ่</strong> โดยในตอนแรกนั้นผมได้ลอง Resize ไปขนาดต่างๆแล้วทำ Train ด้วย Lenet-5 แต่ใช้ TPU Train เลยประหยัดเวลาไปได้เยอะมากทำให้สามารถ Train รูปใหญ่ๆ ได้ โดยผลที่ได้ก็ออกมาดังนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3PzzmIxfrR0MPbvtfc89w.png" /></figure><p>จะเห็นได้ว่ายิ่งผมไปทำให้ภาพมีขนาดเล็กลงประสิทธิภาพก็แย่ลงตาม ผมจึงเลือก Resize ที่ขนาด 456x456 (เดียวผมจะอธิบายเพิ่มเติมว่าทำมัยถึงเลือก 456 )ในตอนสุดท้าย แต่ผมก็สงสัยทำมัย resize มันห่วยขึ้นเลยลอง plot ออกมาดูสักรูปที่ resize ด้วยขนาด 32x32 ก็ได้ดังถาพก็ถึงบางอ้อ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yya13_TZql-KNqXKxCzBdg.png" /></figure><p>แปลว่าการ Resize ตรงๆ คงไม่ใช่เรื่องที่ดี โดยในตอนแรกนั้นผมทำ Sobel edge detection แต่ผลที่ได้ก็ไม่ค่อยต่างจากเดิม แต่ผมก็ได้ไปเห็น Notebook อันหนึ่ง โดยมีคนในกลุ่ม Super AI Engineer ได้แชร์ Notebook อันนี้</p><p><a href="https://www.kaggle.com/layyer/thai-mnist-lenet5">Thai-mnist-Lenet5</a></p><p>จะเป็นของ P’Lay โดยผมชอบ Notebook อันนี้มากเพราะ เคยเรียนในวิชา Algorithm ในส่วน Convex hull แต่ไม่คิดว่าสามารถทำอะไรแบบนี้ในงาน image ได้ด้วย แต่ผมก็ได้ลองใช้ Algorithm <strong>แต่ผลลัพธ์ที่ได้ไปลองกับ Model ไม่ได้ดีกว่าที่ผมทำแบบเดิม ผมจึงไม่ได้ใช้ต่อ (แต่ Notebook ดีมากๆนะครับแนะนำให้ไปดู )</strong></p><p>ผมจึงมานับทบทวนว่าจริงๆแล้วการ Resize อาจจะช่วยแค่เรื่องเวลาของการ Train เพราะยังไงตอนทำ Convolution ใน CNN มันต้องหาทั้งรูปภาพอยู่แล้ว และ อีกอย่างการทำ CNN มันถูกออกแบบมาถ้าเจออะไรในภาพนั้นที่เหมือนกัน มันก็จะใช้ Feture นั้นด้วยกันอยู่แล้ว เพื่อเป็นการลดความซับซ้อน ดังนั้นขนาดภาพอาจไม่ได้เปิดประสิธิภาพ ผมจึงแก้ปัญหาแบบกำปั่นทุบดิน ไหนๆก็มี TPU สุดแสนแรงก็ใช่ให้สุดเลยผมจึงไม่ Resize ให้แค่ขนาดที่พอเหมาะเท่านั้น</p><p><strong>2 Data Imbalance</strong> ปัญหานี้ผมจะมาพูดใน Loss Function ที่ผมใช้เพื่อแก้ปัญหานี้ โดยผมไม่ได้ใช้ Loss แบบทั้วไปเช่น Sparse categorical crossentropy (Softmax) หรือ Categorical Crossentropy (One-hot)ในการ Train</p><p><strong>3 รูปภาพมีความหลากหลายค่อนข้างสูง </strong>จากรูปภาพข้างต้นจะเห็นได้ว่ารูปมีความหนา ความบาง ความชัด และ ตำแหน่ง ต่างกันค่อนข้างมาก แต่ถ้าเรามาพิจรณาดีๆ ภาษาไทยความหนาไม่ได้ส่งผลต่อความหมาย ดังนั้นผมจะไม่แก้ตรงนี้ ในส่วนของ ตำแหน่ง นั้นอย่างที่ผมกล่าวไปข้างต้น CNN มันจะพยามเรียนทั่งรูปอยู่แล้ว ดังนั้นตำแหน่งจึงไม่ใช้ปัญหา ดังนั้นในขั้น Image Processing ในขั้นตอนนี้ผมจึงไม่ได้ทำอะไรไป ร่วมไปถึงการทำ Data augmentation เช่น Rotate , Shift, Flip และ Shering เพราะ เลขไทยค่อนข้างมีผลมากกับการทำอะไรพวกนนี้จึงตัดออกทันที</p><p><strong>4 Noise ที่เยอะมาก</strong> วิธีการแก้ปัญหานั้นก็ง่ายมากนั้นก็คือ “Drop ทิ้ง” โดยในตอนแรกผมนั่งไล่ดูไปประมาณ 3000 รูป แล้วก็หยุดทำเพราะว่ารู้สึกน่าจะเพียงพอ (เหนือยด้วยละ 55555 ) แต่ก็มีพี่ใจดี Clear Noise ให้ ก็คือ <strong>P’ชินธิป 22p24c0002</strong> ซึ่ง Drop Noise ไปเยอะมากว่าผมมาก ของผม 50 ของพี่เขา 300 ต้องขอบคุณ P’ชินธิป มากที่ทุ่มแรงกายจัดจาก Dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*BFzQdROyiT33Od900cVhNg.png" /></figure><h4>Loss function</h4><p>อย่างที่ผมกล่าวไปข้างต้นว่าผมจะใช้ Loss Function มาแก้ปัญหา Imbalance ซึ่งนั้นก็คือ Focal Loss โดย Focal Loss จะอยู่ในงาน Paper ของ <a href="https://arxiv.org/abs/1708.02002"><strong>Focal Loss for Dense Object Detection</strong></a><strong> </strong>แล้วมันคืออะไรละถ้าอางอิงจาก Paper Focal Loss จะพูดถึง Object Detection Model ที่เวลาของต้องการ Detect Class อะไรก็ต้อง Anchor Box แต่ปัญหามันอยู่ตรงนี้ครับ ถ้าใครเคยทำ Object Detection มาก็จะรู้ว่า Anchor Box พวกนี้จะเกิด ที่ Background มากว่า Class ที่เราสนใจโดยใน Paperนี้จะพูดว่าบางครั้งอาจเกิด ด้วยอัตราส่วน 1:1000 นั้นหมายความว่า Model แทบจะเกือบไม่ได้เรียนอะไรเลยจาก Class ที่เราสนใจ แล้ว Focal Loss มันช่วยอะไร โดย Focal Loss นั้นจะพยามลด Loss ใน Class ที่เรียนได้ดีอยู่แล้วให้น้อยลงมากๆ เพื่อสามารถทำให้ Model ไปสนใจ Class ที่ยังเรียนไม่ได้ดี พูดแบบนี้อ่านจะงง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*SKk9t3ZMCEWIDypPcOSuSA.png" /><figcaption><a href="https://medium.com/@ayodeleodubela/what-does-focal-loss-mean-for-training-neural-networks-770636f76379">https://medium.com/@ayodeleodubela/what-does-focal-loss-mean-for-training-neural-networks-770636f76379</a></figcaption></figure><p>โดยให้ลองดูสมมการนี้ก่อน เทียบกับพวก Cross-entropy ตัวอื่นๆ โดยที่ Alpha กับ Gamma คือ Hyperparameter ส่วน Pt คือ Class ที่ Predict โดยเดียวผมจะแสดงตัวอย่างให้ดู</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*tLQ7YZ_L5Moo4f1P9yPWEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*ROxWo4x2m8ebWiQ_nAnODw.png" /><figcaption>ซ้ายคือ Predcit ถูกหมด , ขวาคือ Predcit ผิด 1 อัน</figcaption></figure><p>จากรูปด้านซ้ายจะเห็นได้ว่าถ้า Model predict ถูกหมด ค่า Loss ของ Focal Loss นั้นจะต่ำกว่า Loss Cross-entropy มาก แปลว่า Model กำลังตอบต้องด้วยความมั่นใจที่มาก แต่ถ้า Predict ผิดละ ค่า Loss ก็ต่ำกว่าแต่ไม่ได้ต่างกันมาก แปลว่า Model กำลังตอบด้วยความมั่นใจที่น้อยโดยรวมๆแล้วมันหมายความว่าไงละ โดยเดิมที่ถ้าเรามาดูที่ Loss Function ของ Cross-entropy ในหลายๆ แบบ โดย Cross-entropy จะคำนวณค่าผิดถูกโดยรวมๆ ซึ่งมันจะพยามให้ Model เรียนรู้ในสิ่งที่ตัวเองทำได้ดีอยู่แล้วให้ดียิ่งขึ้นไปอีก อาวแล้วมันยังไงนิก็ดีไม่ไม่ใช่หรอ Model จะได้เก่งไปอีก แต่มันไม่ใช้แบบนั้นครับ ลองคิดว่า <strong>“เราอ่านหนังสือไปสอบแต่เราใช้เวลาอ่านน้อย เราจึงพยามทำแต่ข้อที่ทำได้ ให้ดีมากๆ ส่วนข้อที่ทำไม่ได้ก็จะไม่ทำ” </strong>Deep Learning model ก็เหมือนกันครับมันพยามจะหาทางลัดในการเรียนรู้และพอยิ่งเราใช้ Cross-entropy ก็เหมือนไป สปอย มันอีก เราจึงเลือกใช้ Focal Loss มันจะได้พยามเรียนแต่ในสิ่งที่มันยังทำไม่ได้ดี ส่วนสิ่งที่ทำได้ดีแล้วก็ให้ลดความสนใจ ในกรณีของเราก็คือ Imbalance Class ที่ Model ไม่สามารถเรียนรู้อะไรได้เยอะ เพราะ Data เราน้อยเกินไป Focal Loss พยามจึงทำให้ Model สนใจ Class ที่ Data น้อยๆไว้ก่อน <strong>บางคนอาจคิดว่า Loss มันก็น้อยลงทั่งสอง Case ไม่ใช่หรอ ทำไหม Model จะสนใจ Clsss นี้ดีกว่าได้ ใช่ครับ มันน้อยลงทั่งคู่ แต่อย่าลืมนะครับว่า ใน Class ที่ Model ตอบถูกมันจะตอบด้วยความั่นใจมากๆ ทำให้ค่า Loss น้อยมากๆ แต่อันไหนตอบผิดมันก็น้อยแต่มันก็น้อยไม่มาก แปลว่า เมือเราเอามาบวกกันมันจะเหลือแต่ค่าที่ Loss ที่ตอบผิด แต่ค่า Loss ที่ตอบถูกมันน้อย บวกไ ก็ไม่สร้างนัยสำคัญ เรื่องจากค่ามันน้อย</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXi5uXaxetKBTaOqIk4_gw.png" /></figure><p>โดยผมจะขอไม่พูดถึง Hyperparameter เยอะนะครับเนื่องจากค่อนข้างสามารถอธิบายได้ทั้งบทความเลย เพราะ ผมก็ใช้ค่าต่างๆ จากงาน Paper (ถ้าผมว่างๆ อาจมาอธิบายเพิ่มเติมให้นะครับ) [เพิ่มเติมนะครับ จริงๆ วิธีแก้อีกแบบก็คือ ฺBalance Cross-entropy ในการ weight class ผิดกับถูก แต่ใน Paper ของ Focal Loss บอกไว้ ณ จุดหนึ่ง Balance Cross-entropy ไม่สามารถแก้ไขได้ ]</p><p>แต่ก็ยังไม่หมดเท่านี้ ผมได้ใส่ Label smoothing ลงไปด้วยเพื่อไม่ให้ Model เกิด Over-confidence โดยวิธีการก็คือ ผมจะทำวัน Hot-one encoder เพื่อแสดงถึง class ต่างๆ [1,0,0,0,0,0,0,0,0,] แต่ผมจะไม่ใส่ 1 แบบ นี้แต่จะทำให้เป็น [0.8,0,0,0,0,0,0,0,0,] เพื่อไม่ให้ Model ตอบอะไรแบบสุดโต่งเกินไป</p><p><strong>Learning rate schedules</strong></p><p>ก่อนเราจะ Train ก็มาดู Learning rate อันนี้เป็นอะไรที่ผมอยากแนะนำมากๆ ให้ทุกคนทำ โดยทั่วไปถ้าเรา Train แบบไม่ทำ Learning rate schedules เราจะได้ Learning rate เป็น Constanst แต่ถ้าเราทำแบบนั้นเวลา ณ จุดหนึ่งที่ Epoch มันเยอะมากๆ เราต้องการ Learning rate ที่น้อยมากๆ เพื่อ Model เราจะได้สามารถลง Local Optima ได้ ดังนั้น Learning rate schedules จะมาช่วยเรื่องนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*gT5O_EfPlUr0TGdw2jDQQQ.png" /></figure><p>โดยผมจะมาแนะนำ Cosine Learning rate schedules with warmup ทำไหมผมถึงแนะนำตัวนี้ จริงๆก็ไม่มีเหตุผลหรอกครับ 5555 คือผมลองอ่าน Paper เขาแนะนำมากกลับคนใร Kaggle ก็แนะนำมาเหมือนกัน ซึ่งผมก็ลองใช้ในงานแข่ง Kaggle หลายๆอันก็ได้ผลที่ดีมาก เลยอยากจะมาแนะนำกันไว้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBSml_b8dUkL6wG9IAyOiw.png" /></figure><h4>Train</h4><p>โดยการ Train ของผมนะครับ จะ Train ด้วย TPU ที่ Train ได้รวดเร็วๆสุดแต่มันก็แลกอะไรมาเยอะพอสมควร ตามดังนี้</p><ul><li>เมื่อเรา Train ด้วย TPU เราต้องเก็บไว้ใน Clound Storage ของ Google เป็น path GCP ผมจึงเลือก Train บน Kaggle เพราะมันจะอัพ Dataset ลง GCP ทันที่ (ก็มันของ Google นี้เนาะก็คงไม่แปลก) สาเหตุก็คงมาจากตอนนี้ TPU ยังทำแบบ Commercial ไม่ได้มากจึงต้องพึงพา Environment ของ Google เป็นหลักก่อน ณ ตอนนี้</li><li>ถ้าจะรีดประสิทธิภาพ TPU ได้สูงสุดต้องทำทุกอย่างให้เป็น Tensor ซึ่งหมายความว่า เราต้องใช้แค่ Libary ของ Tensorflow (จริงๆ Pytouch อาจใช้ได้ดีกว่าก็ได้ แต่ผมไม่เคยใช้เลย 55555 ) ซึ่งทำให้เราไม่สามารถใช้ Numpy มาในการทำ Image preprocessing ได้ซึ่งน่าเสียดายมากๆ เนื่องจาก Libary ของ Tensorflow ยังทำ Image processing ได้น้อย เมื่อเทียบกับพวก OpenCV อะไรแบบนี้ (ตอนผมลอง Notebook ของ P’lay ผมก็ได้ไปใช้ GPU ซึ่งนานมากๆๆ ใน Colab เพราะไม่สามารถ map ค่าได้ใน TPU )</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjAnmYaVYLmuw6duV1fRWw.png" /><figcaption>code ตัวอย่างสำหรับทำข้อมูลเป็น Tensor</figcaption></figure><p>ในส่วนของ Model นะครับผมก็ได้ลองหลายตัวมาก ทั่ง Letnet-5, Resnet101, Xception, EfficientNetB3, EfficientNetB4, Easamble modelโดย Easamble model เพื่อทำ Hard voting ที่ผมทำก็จะเป็นดังภาพ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srwGlAhEg46WtOTwfNJYUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u96tlc2dbre07MJmqkcsDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JS-esGPUGa_GmyTmLP3YnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O93tlDeQoSAJB6fXFFT61Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PATXBCVrfJZOv2M3AwLn0Q.png" /></figure><p>และผลลัพธ์ที่ได้จะเป็นดังนี้ (โดยผมจะบันทึกแต่ค่าสุดท้ายนะครับ)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKGMhtK3UVq6ueFw8wqnQw.png" /></figure><p>จะเห็นได้ว่า EfficientNetB3 ได้ผลที่กว่าซะงั้น (จริงๆผมอาจจะยัง stack ไปไม่เยอะพอ อาจได้ผลลัพธ์ที่ดีกว่านี้ก็ได้ ) ผมจึงเลือกทำ EfficientNetB3 แล้ว KFOLD ไปอีกที่ และ ใช้คู่กับ EarlyStoping เพื่อกัน Overfit โดยมันก็จะมาในสาเหตุที่ผมเลือก Image size 456x456 เพราะ Papper ของ EfficientNetB3 แนะนำมา จะได้ผลลัพธ์ดังภาพ (อันนี้เป็น 1 ใน 5 Fold ที่ผมยิบมานะครับ แต่ตามจริงเราควร check ทุก model นะครับว่าประสิทธิภาพใกลเคียงกันรึปร่าว​โดยผมทำการ Check แล้ว ถ้าเจอให้ drop ทิ้งไม่ก็ลอง Train ใหม่)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnoDcssN2-ME4WzTdYE8iw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3tfHnB1Ey0vQZVCqlQ4dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyz8rKIqanJ6ebWcdq9uMg.png" /></figure><p>ใจจริงอยากทำ 10 KFold แต่ติดที่ Kaggle ให้ Session แค่ 3 ชม. ซึ่งถ้าทำ 10 ต้องใช้เวลา 3:30 ชม. (น่าเสียดายมากๆ น่าจะให้สัก 5 ชม.)</p><h3>Regression model</h3><p>มาถึงส่วนที่สองนะครับที่จะทำการสร้าง Regression model เพื่อหาความสัมพันธ์ของข้อมูลของเรา</p><p><strong>Prepare Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IK-H2MO8jA8ycxWH7JUUHA.png" /></figure><p>จะเห็นได้ว่าข้อมูลเรามีค่า NaN อยู่ที่ Feature 1 ค่อนข้างเยอะผมจึง fillna(-1) ไปจะได้ดังภาพ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LtJy8b_1_X3GicJZkzuqtQ.png" /></figure><p>โดยผมจะไม่ทำการ Normalize ข้อมูลเพราะ ยังไงข้อมูลมันก็อยู่ระหว่าง 0–9 ทุก Feature เหมือนกัน ยกเว้น Feature 1 แต่ก็ไม่เป็นไรเราถือเป็น Case พิเศษไป</p><h4>Model</h4><p>ทุกคนคงรู้กันว่า Regression model มีเป็น 10 model Hyperparameter อีก 10 ถ้าลองทั้งหมดคงจะไม่ไหว ผมเลยจะมาแนะนำ Tools ตัวหนึ่งชื่อ <a href="https://pycaret.org/">Pycaret</a> สุดยอด Automate pipline machine learning tools วิธีการใช้ก็ง่ายมากให้ทำการ</p><p>!pip install pycaret</p><p>และให้พิมคำสั่งตามภาพ และ ได้ผลลัพธ์ดังภาพ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCLuPcE3Q5KW4NxjST1QHQ.png" /></figure><p>เท่านี้มันจะทำการสำรวจข้อมูลของเราเพื่อ Preprocess data ต่อมาให้ทำการ Compare model เราจะได้ผลลัพธ์ดังภาพ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymTwoMUoFj0wUnihw5uyjw.png" /></figure><p>จะเห็นได้ว่า Decision Tree ให้ผลลัพธ์ดีที่สุดผมก็ลอง Train อีกรอบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_xzXnYpJcxms5vnvdKlsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1IqMdbYwQ05cUQNTLfmqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGkRaHC79wdiEjw8s4OpzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRSOI2VfyWC-VVBhYOVrOQ.png" /></figure><p>ผมลัพธ์ที่ได้ก็ถือว่าดีมาก แต่!! มันทำได้ดีกว่านี้ มีพี่ๆในกลุ่มได้ทำสุดยอด Feature Engineer ไว้ เป็น Rulebase ซึ่งผลที่ได้ก็คือ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GhVwLdcnx-9vOB8g4Gm1yw.png" /></figure><p>OMG!!! 55555 ต้องขอบคุณพี่ๆ ในกลุ่ม Super AI Engineer ที่ช่วยหามาให้ โดยผมอยากจะคาราวะข้อ 8 มาก ว่าคิดได้ยังไง ผมนั้งคิดเท่าไรก็คิดไม่ออก</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WH8c90bIMRxSM98VWmDI1w.png" /><figcaption>code rule base</figcaption></figure><p>แต่เราเป็น Super AI Engineer ไม่ใช่ Super Rule base Engineer 55555 ก็มาลอง Model ที่ได้หามาหน่อย จึงได้ผลลัพธ์ดังนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNfxdo2grpW4gyhRTLyPXQ.png" /></figure><p>ถือว่าไม่ได้แย่เลยสำหรับ Decision Tree แต่ผมว่าอาจจะมีการปรับเพิ่ม เพื่อกัน Overfit น่าจะได้ผลลัพธ์ได้ดีมากว่านี้</p><h3>Conclusion</h3><p>โดยการแข่งขันครั้งนี้ ผมก็หวังไว้ว่าแค่ติด Top 10 ก็ดีใจมากแล้วแต่ผลลัพธ์ที่ได้เป็น ลำดับที่ 1 ซึ่งว้าวมากๆ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rrjdTDsNPVARBd6SGETwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6965H4EM8lQPvm7BxlZcQw.png" /></figure><p>ก็ด้วยส่วนตัวนั้นผมเป็นคนไม่ได้ค่อยเขียนอะไรบ่อยประมาณ Blog Medium เพราะ ตัวเองเป็นคนเขียนตกหล่น หรือ ใช่คำผิดบ้าง และ ผมก็ขอฝาก Notion ของผมไว้หน่อยผมทำเอาไว้อ่านตอนใกล้สอบ และ ก็อยากเอาไว้แชร์ความรู้กับเพื่อนๆ ด้วย</p><p><a href="https://www.notion.so/6e3db7e225954eed82020a157623038e?v=3641c174d43a4c45a9ec42f634031804">Super AI Engineer</a></p><p>ส่วนอันนี้จะเป็น Code ใน Kaggle นะครับ โดยผมตัดเหลือแต่ส่วนที่สำคัญเท่านั้นนะครับที่ใช้สำหรับ Run ส่ง</p><p><a href="https://www.kaggle.com/natthananbhukan/22p21c0253-natthanan-w4hw1-12102020?scriptVersionId=44902360">22p21c0253_Natthanan_W4HW1_12102020</a></p><p>ถ้ามีอะไรที่ผมเขียนผิด หรือ อยากจะแนะนำสามารถบอกได้ตลอดเลยนะครับ ขอบคุณมากครับ :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=facd332fa500" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy model machine learning ฉบับมือใหม่]]></title>
            <link>https://medium.com/@RTae/deploy-model-machine-learning-%E0%B8%89%E0%B8%9A%E0%B8%B1%E0%B8%9A%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B9%83%E0%B8%AB%E0%B8%A1%E0%B9%88-c54ac5439619?source=rss-57a2f5f364a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c54ac5439619</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Natthanan Bhukan]]></dc:creator>
            <pubDate>Sun, 23 Aug 2020 14:06:45 GMT</pubDate>
            <atom:updated>2020-08-28T18:41:50.251Z</atom:updated>
            <content:encoded><![CDATA[<p>เมื่อเราทำงานแล้วต้องการนำ Machine Learning มาใส่ในงานเรา ก็คงไม่ค่อยมีปัญหาถ้าเราทำในงานวิเคราะห์ข้อมูลส่วนตัว เพราะ มีแค่ Jupyter notebook หรือ Colab ก็สามารถทำได้แล้ว แต่ถ้าเราอยากให้คนอื่นใช้ด้วยละ หรือ เราอยากทำเป็น tools ที่เรียกใช้เมื่อไรก็ได้ แบบนี้ต้องทำยังไง ?</p><p>วันนี้ผมจะมาพูดถึงการ Deploy Machine learning ฉบับมือใหม่ ไม่ config เยอะ เน้นผลลัพธ์ที่เห็นได้ชัดก่อน หรือ ก็คือ Prototype นั้นเอง โดยขั้นตอนคร่าวๆ จะมีดังนี้</p><ul><li>Train Model — แน่นอนครับว่าก่อนจะทำ Deploy อะไร ก็ต้องมี Model ก่อน ซึ่งใน<strong>บทความนี้จะไม่ลงลึกเรื่องเนื้อหาของ Model นะครับ</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWgVDMI21G7CC0_Fad-LVA.jpeg" /><figcaption>Train model diagram</figcaption></figure><ul><li>Save model — หลังจากเรา Tune Model จนพอใจแล้ว เราจะทำการ Save model and weight เก็บไว้ แล้วเอามาเรียกใช้ทีหลัง เพื่อทำ Pipeline สำหรับ Predict กันต่อนะครับ <strong>ในบทความไม่ได้สอนวิธีการ Save นะครับจะเป็นการดึงมาใช้เลย</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbDYMCfHOZFjEzBp_q8aBw.jpeg" /><figcaption>Save model diagram</figcaption></figure><ul><li>API — หลังจากมี Pipeline สำหรับ Predict ให้ทำการแยกไฟล์ไว้ แล้วทำการสร้าง API ต่อ เพื่อให้คนอื่นสามารถใช้ Model ของเราได้ หรือเป็น Tools ที่เรียกใช้ได้ตลอด เมื่อ User request มา</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWy2nJRXcEffZ2KiPEE-Fg.jpeg" /><figcaption>API Diagram</figcaption></figure><ul><li>Deploy — เมื่อทดสอบใน Local เสร็จ แล้วไม่ปัญหา เราก็ถึงขั้นตอนสุดท้าย ก็คือการ Deploy โดยบทความนี้จะเน้น config น้อยๆไว้ก่อน เพื่อให้เป็นแนวทางต่อ ยอดได้</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPhm_dqJqKL1z17BKPWPIw.jpeg" /><figcaption>Deploy Diagram</figcaption></figure><h3>Load Model</h3><p>ในขั้นนี้เราจะทำการ Load model หลังจากที่ได้ทำการ Train และ Save เพื่อใช้ในการสร้าง Pipeline สำหรับทำ Predict โดยของผมจะเป็น Model สำหรับ image จะมีตัวอย่างข้างล่างดังนี้ (model สามารถเป็น format แล้วแต่ที่ใช้ได้นะครับ โดยวิธีการเขียนก็จะคล้ายๆ กัน จากตัวอย่างจะเป็น .h5) ให้ทำการสร้าง File แยกไว้เพื่อง่ายต่อการ Debug กับการจัดการ File</p><pre><strong># ML_APP.py</strong></pre><pre>from tensorflow import keras<br>import numpy as np<br>import cv2</pre><pre>#Load model<br>model = keras.models.load_model(&#39;./my_model.h5&#39;)<br>classDict = {<br>  0: &#39;cardboard&#39;,<br>  1: &#39;glass&#39;,<br>  2: &#39;metal&#39;,<br>  3: &#39;paper&#39;,<br>  4: &#39;plastic&#39;,<br>  5: &#39;trash&#39;<br>}</pre><pre># Create pipeline<br>def predictImage(image):<br>  image = cv2.resize(image, <br>                     (100,100),    <br>                     interpolation = cv2.INTER_AREA<br>                    )<br>  image = np.reshape(image, [1, 100, 100, 3])<br>  prob = model.predict(image)<br>  predict = np.argmax(prob)<br>  label = classDict[predict]<br>  confident = prob[0][predict]<br>  return label, confident</pre><h3>API</h3><p>หลังจากทำ Pipline สำหรับ Predict เราก็จะทำ API โดยในทีนี้ ผมจะเลือกใช้ Flask ถ้าใครถนัดตัวอื่นก็สามารถใช้ได้นะครับ โดยสาเหตุที่เลือก Flask เนื่องจากไม่ต้องมีการ config ที่เยอะจึงสะดวกสบาย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Q0_XhTIdb5-krvMsXSDs9g.png" /><figcaption>Flask <a href="https://flask.palletsprojects.com/en/1.1.x/">link</a></figcaption></figure><p>โดยตัวอย่าง Code จะเป็นดังนี้</p><pre><strong># main.py</strong></pre><pre>from flask import Flask, flash, request ,jsonify, render_template<br>from werkzeug.utils import secure_filename<br>from ML_APP import * <strong># ทำการ import predict เข้ามา</strong><br>import json<br>import cv2<br>import os</pre><pre>UPLOAD_FOLDER = &#39;./uploads&#39;<br>ALLOWED_EXTENSIONS = {&#39;png&#39;, &#39;jpg&#39;, &#39;jpeg&#39;}</pre><pre>application = Flask(__name__)<br>application.config[&#39;UPLOAD_FOLDER&#39;] = UPLOAD_FOLDER</pre><pre>def allowed_file(filename):<br>    return &#39;.&#39; in filename and filename.rsplit(&#39;.&#39;, 1)[1].lower() <br>                              in ALLOWED_EXTENSIONS</pre><pre><strong># สร้าง Home Page</strong><br>@application.route(&#39;/&#39;) <br>  def main():<br>  return &#39;Hello This is home page&#39;<br></pre><pre><strong># สร้าง Request สำหรับ model</strong><br>@application.route(&#39;/upload&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;]) <br>  def upload_file():<br>  if request.method == &#39;POST&#39;: # ต้องผ่าน Post Medthod เท่านั้น<br>  <strong># ถ้าไม่มีไฟล์แนบมา</strong><br>    if &#39;file&#39; not in request.files:<br>    flash(&#39;No file part&#39;)<br>    return &#39;No file part&#39;<br>    <br>    file = request.files[&#39;file&#39;]<br>    <strong># ถ้า User ไม่แนบไฟล์มา</strong><br>    if file.filename == &#39;&#39;:<br>      flash(&#39;No selected file&#39;)<br>      return &#39;No selected file&#39;<br>       <br>   <strong> # ถ้ามีFileและtype ถูกต้อง</strong><br>    if file and allowed_file(file.filename):<br>      filename = secure_filename(file.filename)</pre><pre>      <strong># Save File</strong><br>      file.save(os.path.join(application.config[&#39;UPLOAD_FOLDER&#39;],    <br>                             &#39;image.png&#39;))</pre><pre>     <strong> #Load ภาพที่ Save ไว้</strong><br>      img = cv2.imread(&#39;./uploads/image.png&#39;) </pre><pre>     <strong> # นำรูปไปใส่ใน Model </strong><br>      label, confident = predictImage(img)<br>      return jsonify({<br>                     &#39;label&#39;: label ,</pre><pre>                     &#39;confident&#39;: json.dumps(str(confident))</pre><pre>                    })<br>  return render_template(&#39;upload.html&#39;)<br></pre><pre>if __name__ == &#39;__main__&#39;:<br>  application.debug = False<br>  application.run(host=&#39;0.0.0.0&#39;, port=8080)</pre><p>โดย Flask สามารถทำหน้าที่เป็น Template ได้ โดยผมได้ทำเป็นหน้า Upload ไฟล์ มี Code ดังนี้</p><pre><strong>&lt;!--- ./templates/upload.html ---&gt;</strong></pre><pre>&lt;!doctype html&gt;<br>&lt;title&gt;Upload new File&lt;/title&gt;<br>&lt;h1&gt;Upload new File&lt;/h1&gt;<br>&lt;form method=post enctype=multipart/form-data&gt;<br>  &lt;input type=file name=file&gt;<br>  &lt;input type=submit value=Upload&gt;<br>&lt;/form&gt;</pre><p>ในการทดสอบบน Local ให้ทำการเปลี่ยนสองบรรทัดสุดท้ายให้เป็นแบบข้างล่างนี้ก่อน</p><pre>application.debug = True<br>#application.run(host=&#39;0.0.0.0&#39;, port=8080)<br>application.run()</pre><p>ในขั้นตอนต่อไป เราจะทำการทดสอบก่อน แต่เราต้องทำการสร้าง Enviroment มาให้มันก่อนโดยทำการพิมพ์คำสั่งข้างล่างนี้ก่อน</p><pre>pip install pipenv</pre><p>ถ้าใครใช้ Mac ก็ brew มาได้นะครับ</p><pre>brew install pipenv</pre><blockquote>สามารถใช้พวก Environment ตัวอื่นได้นะครับ เช่น Conda</blockquote><p>หลังจากลงเสร็จแล้วให้พิมพ์คำสั่งนี้โดยมันจะยึด python version ของเครื่องเป็นหลัก</p><pre>pipenv shell</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zY4B1sHHuRtsywpZq7RiYg.png" /></figure><p>เมื่อได้แบบนี้แล้วก็แปลว่า ได้สร้าง Environment เรียบร้อย ต่อไปให้พิมพ์คำสั่งนี้เพื่อเป็นการ ติดตั้ง libary ที่จำเป็น ลำดับแรกก็เป็น Flask ที่เราใช้ทำ API ต่อมาผมจะลงสำหรับทำ Machine learning ของผม ซึ่งก็จะมี Tensorflow กับ openCV ซึ่งอันนี้จะเป็น Optional สำหรับของแต่ละคนเลย</p><pre><em>pipenv install Flask tensorflow </em>opencv-python</pre><p>หลังจากลงเสร็จเรียบร้อยให้ทำการพิมพ์ตามนี้</p><pre>python main.py</pre><p>จะได้ดังภาพนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bJ7kvb4lSvBG2Gpg-rbuw.png" /><figcaption>Test on local</figcaption></figure><p>ให้ลองทดสอบ API ดูว่าเป็นตามที่เราต้องการรึเปล่า</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbKcUs4EYl0Vm_d4N1sH1A.png" /><figcaption>Home page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8U8yEZBLz1B28qD8QX4hXw.png" /><figcaption>Upload page with out upload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RxQRWWAhNMsEX0sXS1PrcQ.png" /><figcaption>Upload page with upload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Y6nMCHCS4md6GGOo_KieA.png" /><figcaption>Upload page result</figcaption></figure><p>และก็ทดสอบกับ Postman ได้ผลดังภาพข้างล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTzPqgKby3GhL4zG3st24g.png" /><figcaption>Test with postman <a href="https://www.postman.com/">link</a></figcaption></figure><blockquote>ปล. อย่าพึ่งตกใจว่าทำไมค่า Confident เกินหนึ่ง อันนี้ยังเป็น model demo ต้องมีการจัดการ train กับ วาง layer ให้ดีกว่านี้</blockquote><p>หลังจากทำการทดสอบจนมั่นใจว่าไม่น่ามีปัญหา ให้ทำการเปลี่ยนสองบรรทัดสุดท้ายใน file app.py ให้เป็นแบบข้างล่างนี้</p><pre>application.debug = False<br>application.run(host=&#39;0.0.0.0&#39;, port=8080)</pre><h3><strong>Deploy</strong></h3><p>โดยในขั้น Deploy นะครับ ผมจะ deploy ลง AWS โดยใช้ EC2 เป็น VM ในการ deploy API ของเรา</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*lKyql2X1yTaeW0yoUSlsVQ.jpeg" /><figcaption>EC2 <a href="https://aws.amazon.com/th/ec2/">link</a></figcaption></figure><p>ก่อนอื่นให้ทำการสมัคร AWS และ login ให้เรียบร้อย (ต้องกรอกข้อมูลบัตรด้วยนะครับ แต่เราจะใช้แบบ free ไม่ต้องกังวล) เมื่อทำการ Login เสร็จแล้ว จะได้หน้าแบบข้างล่างนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTDk7XFcPBl8AAjxuGW2ow.png" /><figcaption>AWS Console</figcaption></figure><p>ในช่อง Find Services ให้ Search หาคำว่า EC2 แล้วทำการเลือกไปดังรูปข้างล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fL6EXNtFim0mjBw270HvA.png" /><figcaption>Search for ec2</figcaption></figure><p>จะได้หน้านี้ขึ้นมาให้ทำการเลือก Instancesc และ ก็ Launch Instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMQ7yhMROO6_GiFYCaoicw.png" /><figcaption>Select Instance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujJeRDNFxPpVrk5oiaWMdA.png" /><figcaption>Launch Instance</figcaption></figure><p>จะได้หน้านี้ขึ้นมาให้ทำการ Search หา Ubuntu และให้ทำการเลือกอันที่ 1 โดยการกด Select</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_ypA-kPT4iXSSf1e9zDVw.png" /><figcaption>Select Ubuntu image</figcaption></figure><p>ให้ทำการเลือกแบบนี้ จะได้จะไม่เสียเงิน หรือ ถ้าใครไม่พอใจสามารถเลือกแบบอื่นได้ตั้งแต่ image และ ต่อไปทำการกด Review and Launch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJK4DTd2259iFjh966ZWRg.png" /></figure><p>หลังจากนั้น AWS จะขึ้นหน้าสรุป ให้เราทำการ กด Launch จะมีหน้าให้ทำ Create new key pair ให้ทำการ เลือก Dialog เป็น “Create a new key pair” โดย Key pair name แล้วแต่เรา พอตั้งชื่อเสร็จให้กด Download key pair และ กด Launch Instances</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r283hs9b3eR8ms8vtFf2Bw.png" /><figcaption>create a new key pair</figcaption></figure><p>เราทำการตั้งชื่อ Instances ของเรา หลัง Icon loading</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ai8Np7A4udcYPMPqXjO2Bw.png" /><figcaption>Rename Instances</figcaption></figure><p>ต่อมาต้องทำการ Create Security Groups ทำให้สามารถ Access จากภายนอกได้ ให้ทำการเลือก Security Groups และเลือก Create Security Groups</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NW9ZxDaHi3zTFJ37QnGVHg.png" /><figcaption>Select Security Groups</figcaption></figure><p>สามารถตั้งชื่อกับเขียน Description ได้ตามใจ แต่ Dialog ให้ทำการเลือกตามนี้ และ กด Create</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAcKdHAJsDZ_R1sS3m4k_Q.png" /><figcaption>Config Create Security Groups</figcaption></figure><p>ต่อมาทำการเลือก Network Interfaces แล้วเราทำการ Click ขวา เลือก Change Security Groups ของ Instance ที่เราสร้าง โดยให้ดูจาก Instance ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXYeQQxO2C4hPfX16twHiA.png" /><figcaption>Change Security Groups</figcaption></figure><p>ทำการเลือก Security Groups ที่พึ่งสร้างไป แล้ว กด Save</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6tJpJmGLSH4rgFbyOwl8A.png" /><figcaption>Select Security Groups</figcaption></figure><p>ต่อมาจะทำการกดทดสอบ remote เข้า VM ของเราให้ทำการ copy keypair ที่พึ่งสร้างไปอยู่ไว้คู่กับ Project folder ของเราเพื่อง่ายต่อการทำงาน โดยกลับไปที่ Instances แล้วทำการ เลือก Instance ของเราแล้ว กด Connet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CT8j38JdXnLrz5cTY6hq-g.png" /><figcaption>Remote VM</figcaption></figure><p>จะขึ้น Pop up อันนี้ขึ้นมาเป็นแนะนำการ Connect โดยผมจะได้ ssh สำหรับ window ให้ load putty มาใช้ <a href="https://www.putty.org/">link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4_mBTeTsfdA3eHUdb6Cdg.png" /><figcaption>Connect to VM</figcaption></figure><p>ให้ทำการ Copy จากตัวอย่างมาดังภาพนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTOrxtVNWHZx9ESZvSdYbA.png" /><figcaption>SSH</figcaption></figure><p>ก็จะได้ดังภาพนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smfRa0OtLyKueBOnbCI8Jw.png" /><figcaption>Remote</figcaption></figure><p>ในขั้นตอนแรกให้พิมพ์คำสั้งนี้ก่อนตามลำดับ</p><pre>mkdir model</pre><pre>sudo apt-get update &amp;&amp; sudo apt-get install python3-pip<br>sudo apt-get install -y libgl1-mesa-dev<br>sudo pip3 install -U pip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCW3aLNdbZ9J5ONgQrnlqg.png" /><figcaption>Install pip</figcaption></figure><p>ในขั้นตอนนี้ผมจะทำการ move file จาก local ของเราไปที่ VM แต่ลำดับแรกให้ใช้ Terminal ของเรา CD ไปที่ folder API ของเราแล้วทำการพิมพ์ และพิมพ์วิธีการ move ไฟล์ต่อโดย windows ให้ใช้ WinSCP <a href="https://winscp.net/eng/index.php">link</a></p><pre>pip freeze &gt; requirements.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxV7iYhtQky0RaF8OEDvHw.png" /><figcaption>requirements.txt</figcaption></figure><pre>scp -i &quot;./path/to/ketpair.pem&quot; -r * <a href="/service/mailto:ubuntu@ec2-54-255-201-71.ap-southeast-1.compute.amazonaws.com">user@</a>aws-instance:./model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgjjMLJGYAVakGXENAU8zQ.png" /><figcaption>Move file</figcaption></figure><p>จะได้ดังภาพ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DJkrL95vclVqvXPf8J0TQ.png" /><figcaption>Move file done</figcaption></figure><p>ทำการสร้าง Environment ก่อน</p><pre>sudo apt-get install python3-venv<br>python3 -m venv myenv<br>source myenv/bin/activate</pre><p>และก็ทำการพิมพ์ดังข้างล่างเพื่อทำการ install package</p><pre>sudo pip3 install -r requirements.txt</pre><p>ถ้าตอน run แล้วมัน Error module not found ให้ทำการ sudo pip3 ไปที่ module โดยตรง และ ตอน run ก็พิมพ์คำสั่งข้างล่างจะได้ดังภาพ</p><pre>sudo ufw allow 8080 &lt;-- ทำแค่ครั้งแรกพอ</pre><pre>sudo python3 main.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8stSfbYzQpd_bybmeoloEw.png" /><figcaption>Run</figcaption></figure><p>ทำการทดสอบโดยการ Copy link ที่ Highlight แล้วเติม:8080 ลงไป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-uu1FXNrh8WUlP3X8Ct6w.png" /><figcaption>Copy Url</figcaption></figure><p>จะได้ดังภาพนี้ และถ้าไม่มีปัญหาให้กด command + C (Ctrl + C)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZDZVVuZWHcBjIIiKRlC9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCnjm9UwAWoKjFLPjX7vqg.png" /><figcaption>Test</figcaption></figure><p>ต่อมาให้พิมพ์คำสั่งตามนี้</p><pre>sudo pip3 install wheel<br>sudo pip3 install gunicorn<br>nano ./wsgi.py</pre><p>และข้างใน file ให้พิมพ์ตามนี้</p><pre>from main import application<br><br>if __name__ == &quot;__main__&quot;:<br>    application.run()</pre><p>และทำการพิมพ์</p><pre>gunicorn — bind 0.0.0.0:8080 wsgi:applcation</pre><p>ให้ทำการปิดหน้า Terminal ไปเลยและจะได้ API เรียบร้อย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPi8rG_Xe9461QEayp1eDg.png" /><figcaption>API</figcaption></figure><h3>สรุป</h3><ul><li>API นี้ไม่ได้เน้น Config ให้ยุ่งยาก มีจุดประสงค์คือการปล่อย Prototype</li><li>ถ้าทำในระดับ Production ควรมีการ Config ที่ดีกว่านี้ทั้ง Security กับ environment</li><li>ควรให้ Run บน system ของ VM</li><li>ถ้าไฟล์ไม่ใหญ่มาก แนะนำ Heroku หรือ aws elastic beanstalk ดีกว่า เพราะอันนี้เราไม่ต้อง config เอง แต่ก็แลกมาด้วย disk size ที่น้อยลง</li><li>ควรทำ Load balancer ใน AWS</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c54ac5439619" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>