<?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 Ethan Kuo on Medium]]></title>
        <description><![CDATA[Stories by Ethan Kuo on Medium]]></description>
        <link>https://medium.com/@ethankuo_74456?source=rss-67d1ee087263------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_3TZ_gSqvyf6FUAKv4eT4A.jpeg</url>
            <title>Stories by Ethan Kuo on Medium</title>
            <link>https://medium.com/@ethankuo_74456?source=rss-67d1ee087263------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:03:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ethankuo_74456/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[手把手帶你在WSL環境下建立Multimodal -RAG Chatbot 應用專案]]></title>
            <link>https://medium.com/@ethankuo_74456/%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%B6%E4%BD%A0%E5%9C%A8wsl%E7%92%B0%E5%A2%83%E4%B8%8B%E5%BB%BA%E7%AB%8Bmultimodal-rag-chatbot-%E6%87%89%E7%94%A8%E5%B0%88%E6%A1%88-469930d6fa68?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/469930d6fa68</guid>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 08:44:30 GMT</pubDate>
            <atom:updated>2024-12-04T08:44:30.349Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>前言</strong></p><p>隨著多模態模型的發展，多模態檢索增強生成（Multimodal RAG）應用逐漸興起，然而多種數據輸入格式增加了資料處理的複雜性，要求系統具備更強的解析能力，此外處理多模態數據會導致延遲，這類應用的高運算需求需要強大的計算資源</p><p>本文將深入探討 NVIDIA 的開源專案，透過實際操作來解析其工具整合的應用。此專案源自 NVIDIA 的 LLM 開發者倡導者 Jay Rodge 在九月初的技術分享會上發表的主題：「透過 NVIDIA 與開源模型技術整合，加速多模態 RAG 應用」，並已加進<a href="https://github.com/NVIDIA/GenerativeAIExamples/blob/main/community/multimodal-rag/README.md">GenerativeAIExamples</a>的開源專案中，9/24再看變成<a href="https://github.com/NVIDIA/GenerativeAIExamples/tree/main/community/multimodal_assistant">此連結</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_VOFHwEKb7fYcteeihPFw.png" /><figcaption>支援GPU加速的多模態RAG應用</figcaption></figure><p>專案特色：</p><p>用戶提示經由 <strong>LlamaIndex</strong> 框架進行管理，首先通過 <strong>NV Embed</strong> 進行嵌入處理，然後透過 <strong>Milvus</strong> 向量數據庫進行相關數據檢索，最終將結果返回給 <strong>Llama 3</strong> 基礎模型以生成回應。</p><ol><li><strong>LlamaIndex 框架</strong>：專為管理大語言模型（LLMs）之間的交互設計，負責資料的檢索、排序及輸出結果的優化。</li><li><strong>NV Embed on NIM</strong>：通過整合 <strong>NeVA 22B</strong> 和 <strong>DePlot</strong> 模型，將多模態文件轉換為可嵌入向量的文本格式。並使用<strong>Llama 3 </strong>處理用戶提示，結合檢索到的資料生成高質量回應。</li><li><strong>向量數據庫 Milvus</strong>：基於 GPU 加速技術的高效向量檢索系統，實現對嵌入數據的快速檢索和處理。</li><li><strong>NeVA 22B</strong>：一款專門處理文本與圖像的生成模型，負責將多模態數據進行解析和轉化，生成可用的文本內容。</li><li><strong>DePlot</strong>：專門負責圖表生成與數據可視化，將圖像和數據集進行解析並轉換成視覺化的輸出結果。</li><li>Streamlit UI介面</li></ol><p><strong>一、環境建立</strong></p><p>我們需要先做以下步驟</p><p><strong>1.1 Cuda 驅動程式版本更新<br>1.2 安裝 WSL2 Ubuntu-22.04及 Miniconda<br>1.2 安裝 Docker<br>1.3 安裝 NVIDIA Container Toolkit(</strong>參考<a href="https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html">本指南</a>)<strong><br>1.4 申請 NVIDIA NIM API KEY</strong></p><p>參考這篇文章</p><p><strong>二、安裝支援GPU加速的 Milvus 向量資料庫</strong></p><p>支援 GPU 的 Milvus 硬體和軟體要求: 建議使用545以上版本的驅動程式，且GPU 設備的計算能力必須為以下之一：6.0、7.0、7.5、8.0、8.6、9.0。要檢查您的 GPU 裝置是否滿足要求，請在 NVIDIA 開發人員網站上查看您的 <a href="https://developer.nvidia.com/cuda-gpus">GPU 計算能力</a>。</p><p><strong>2.1 下載並設定 YAML 檔</strong></p><p>使用以下命令下載<a href="https://github.com/milvus-io/milvus/releases/download/v2.4.10/milvus-standalone-docker-compose-gpu.yml">milvus-standalone-docker-compose-gpu.yml</a>並將其另存為 docker-compose.yml 。</p><pre>wget https://github.com/milvus-io/milvus/releases/download/v2.4.10/milvus-standalone-docker-compose-gpu.yml -O docker-compose.yml</pre><p>您需要對 YAML 檔中獨立服務的環境變數進行一些更改，如下所示：</p><ul><li>如需為 Milvus 分配特定的 GPU 設備，在服務定義中找到該欄位，並將其值替換為所需 GPU 的 ID。您可以使用 NVIDIA GPU 顯示驅動程式附帶的工具來確定 GPU 裝置的 ID。Milvus 支援多個 GPU 設備。deploy.resources.reservations.devices[0].devices_idsstandalone</li></ul><p>2.2 為 Milvus 分配單/多個 GPU 設備：</p><pre>...<br>standalone:<br>  ...<br>  deploy:<br>    resources:<br>      reservations:<br>        devices:<br>          - driver: nvidia<br>            capabilities: [&quot;gpu&quot;]<br>            device_ids: [&quot;0&quot;]<br>...</pre><p>將多個 GPU 設備分配給 Milvus：</p><pre>...<br>standalone:<br>  ...<br>  deploy:<br>    resources:<br>      reservations:<br>        devices:<br>          - driver: nvidia<br>            capabilities: [&quot;gpu&quot;]<br>            device_ids: [&#39;0&#39;, &#39;1&#39;]<br>...</pre><p><strong>2.3 啟動 Milvus</strong></p><p>在保存 docker-compose.yml 的目錄中，通過運行以下命令啟動 Milvus：</p><pre>sudo docker compose up -d<br><br>Creating milvus-etcd  ... done<br>Creating milvus-minio ... done<br>Creating milvus-standalone ... done</pre><ul><li>名為 milvus-standalone、milvus-minio 和 milvus-etcd 的容器已啟動。</li><li>milvus-etcd 容器不會向主機暴露任何埠，並將其資料映射到當前資料夾中的 volumes/etcd。</li><li>milvus-minio 容器使用預設身份驗證憑證在本地提供埠 9090 和 9091，並將其數據映射到當前資料夾中的 volumes/minio。</li><li>milvus-standalone 容器使用預設設置在本地提供埠 <strong>19530</strong>，並將其數據映射到當前資料夾中的 volumes/milvus。</li></ul><p><strong>2.4 配置</strong>Milvus<strong>記憶體</strong></p><p>Milvus 啟動並運行後，你可以通過修改milvus.yaml檔中的設置來自定義記憶體池。該文件位於 Milvus 容器內的目錄中</p><p>要配置記憶體池，請按如下方式修改檔中的 and 設置</p><ol><li>使用以下命令從 Milvus 容器複製到本地電腦。替換為你的實際 Milvus 容器 ID。milvus.yaml&lt;milvus_container_id&gt;</li></ol><pre>docker cp &lt;milvus_container_id&gt;:/milvus/configs/milvus.yaml milvus.yaml</pre><p>2. 找到路徑打開milvus.yaml檔案</p><p>3. 根據需要編輯 and 設定並儲存變更：initMemSize maxMemSize</p><pre>...<br>gpu:<br>  initMemSize: 0<br>  maxMemSize: 0<br>...</pre><ul><li>initMemSize：記憶體池的初始大小。預設為 1024。</li><li>maxMemSize：記憶體池的最大大小。預設為 2048。</li></ul><p>4. 使用以下命令將修改後的檔複製回 Milvus 容器。替換為你的實際 Milvus 容器 ID。milvus.yaml&lt;milvus_container_id&gt;</p><pre>docker cp milvus.yaml &lt;milvus_container_id&gt;:/milvus/configs/milvus.yaml</pre><p>5. 重啟 Milvus 容器以應用變更：</p><pre>docker stop &lt;milvus_container_id&gt; docker start &lt;milvus_container_id&gt;</pre><p><a href="https://milvus.io/docs/install_standalone-docker-compose-gpu.md">Run Milvus with GPU Support Using Docker Compose | Milvus Documentation</a></p><p><strong>三、下載專案及安裝套件</strong></p><pre>git clone https://github.com/NVIDIA/GenerativeAIExamples.git<br>cd GenerativeAIExamples/community/multimodal_rag<br><br>pip install -r requirements.txt<br><br><br>source ~/.bashrc<br><br>conda activate multimodal-rag<br><br>cd multumodal-rag/GenerativeAIExamples/community/multimodal-rag<br><br>export NVIDIA_API_KEY=&quot;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&quot;<br><br>sudo docker compose up -d<br><br>docker ps<br><br>streamlit run app.py<br><br><br>git clone https://github.com/NVIDIA/GenerativeAIExamples.gitcd GenerativeAIExamples/community/multimodal_ragpip install -r requests.txtsource ~/.bashrcconda 啟動 multimodal-ragcd multumodal-rag/txtsource ~/.bashrcconda 啟動 multimodal-ragcd multumod vIKPx12HvHhYynlgwA7-DA4WesLQfa62QrqsT4GCsfE5cXMnYDIT7MmleiISz-9e&quot;sudo docker compose up -ddocker psstreamlit run app.pygit clone https://github.com/NVIDIA/GenerativeAIExamples.gitcd GenerativeAIExamples/community/multimodal_ragpip install -r requests.txtsource ~/.bashrcconda 啟動 multimodal-ragcd multumodal-rag/txtsource ~/.bashrcconda 啟動 multimodal-ragcd multumod F6ZhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5h4NGS1_2qABn0FzQL5-JkmqM1CoisiN&quot;sudo docker compose up -ddocker psstreamlit 運行 Genapp.pygitm 克隆 https://github.com/ID/Es/alat/Foneed/Fidal） ip install -r requests.txtsource ~/.bash rcconda 啟動multimodal-ragcd multimodal - rag/txtsource ~/.bashrcconda 啟動 multimodal-ragcd multumod vIKPx12HvHhYynlgwA7-DA4WesLQfa62QrqsT4GCsfE5cXMnYDIT7MmleiISz-9e&quot;sudo docker dockergit clone https://github.com/NVIDIA/GenerativeAIExamples.gitcd GenerativeAIExamples/community/multimodal_ragpip install -r requests.txtsource ~/.bashrcconda 啟動 multimodal-ragcd multumodal-rag/txtsource ~/.bashrcconda 啟動 multimodal-ragcd multumod F6ZhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5h4NGS1_2qABn0FzQL5-JkmqM1CoisiN&quot;sudo docker compose up -ddocker psstreamlit 運行 Genapp.pygitm 克隆 https://github.com/ID/Es/alat/Foneed/Fidal） ip install -r requests.txtsource ~/.bash rcconda 啟動multimodal-ragcd multimodal - rag/txtsource ~/.bashrcconda 啟動multimodal-ragcd multumod vIKPx12HvHhYynlgwA7-DA4WesLQfa62QrqsT4GCsfE5cXMnYDIT7MmleiISz-9e&quot;sudo docker ​​Unap. Examples.gitcd GenerativeAIExamples/社區/multimodal_ragpip 安裝- r requests.txtsource ~/.bashrcconda 啟動multimodal-ragcd multumodal-rag/txtsource ~/.bashrcconda 啟動multimodal-ragcd multumod F6ZhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5hhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5hhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5h4NGS1251305030305 月cker psstreamlit 運行Genapp.pygit m 克隆https://github. com/ ID/Es/alat/Foneed/Fidal） ip install -r requests.txtsource ~/.bash rcconda 啟動multimodal-ragcd multimodal - rag/txtsource ~/.bashrcconda 啟動multimodal-ragcd multumods vIKPx12HvHynY* mleiISz-9e&quot;sudo泊塢窗git clone https://github.com/NVIDIA/GenerativeAIExamples.gitcd GenerativeAIExamples/community/multimodal_ragpip install -r requests.txtsource ~/.bashrcconda 啟動 multimodal-ragcd multumodal-rag/txtsource ~/.bashrcconda 啟動 multimodal-ragcdmultumodal-rag/ F6ZhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5h4NGS1_2qABn0FzQL5-JkmqM1CoisiN&quot;sudo docker compose up -ddocker psstreamlit 運行 Genapp.pygitm 克隆 https://github.com/ID/Es/moles/Uampers/Ferative ip install -r requests.txtsource ~/.bash rcconda 啟動multimodal-ragcd multimodal - rag/txtsource ~/.bashrcconda 啟動multimodal-ragcd multumod vIKPx12HvHhYynlgwA7-DA4WesLQfa62QrqsT4GCsfE5cXMnYDIT7MmleiISz-9e&quot;sudo docker ​​Um​​D -crunc​​U​​cyc​​c​​ck un​​思7 月Examples.gitcd GenerativeAIExamples/社區/multimodal_ragpip 安裝- r requests.txtsource ~/.bashrcconda 啟動multimodal-ragcd multumodal-rag/txtsource ~/.bashrcconda 啟動multimodal-ragcd multumod F6ZhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5hhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5hhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5h4NGS1251305030305 月cker psstreamlit 運行Genapp.pygit m 克隆https://github. com/ ID/Es/alat/Foneed/Fidal） ip install -r requests.txtsource ~/.bash rcconda 啟動multimodal-ragcd multimodal - rag/txtsource ~/.bashrcconda 啟動multimodal-ragcd multumods vIKPx12HvHynY* mleiISz-9e&quot;sudo dockergit複製https://github.com/NVIDIA/GenerativeAIExamples.gitcd GenerativeAIExamples/community/multimodal_ragpip install -r requests.txtsource ~/.bashrcconda 啟動multimodal-ragcd multumodal-A小時/Mul哪裡 ~音/~basculcc​​hkkonealjalkald multus 是SwalxSwykaadin不是alxincxi身&#39;odMult&#39;alkalkhixs/SkalkdoneSwalkdoSdSwulkaldodSwulkdodSwulkooSdSjMdo 是SwoneSj; 8e0l4s5h4NGS1_2qAB n0FzQL5- JkmqM1CoisiN&quot; sudo docker compose up -ddocker psstreamlit 運行Genapp.pygitm 克隆https://github.com/ID/Es/alat/Foneed/Fidal） ip install -r requests.txtsource ~/.bash rcconda 啟動multimodal-ragcd multimodal - rag/ txtsource ~/.bashrcconda 啟動multimodal-ragcd multumod vIKPx12HvHhYynlgwA7-DA4WesLQfa62QrqsT4GCsfE5cXMnYDIT7MmleiISz-9e&quot;sudo dockersfE5cXMnYDIT7MmleiISz-9e&quot;sudo docker Unap. Examples.gitcd GenerativeAIExamples/社群/multimodal_ragpip 安裝- r requests.txtsource ~/.bashrcconda 啟動multimodal-ragcd multumodal-rag/txtsource ~/.bashrcconda 啟動multimodal-ragcd multumod F6Z Wdnnk5E8e0l 4s5hhhwMi_H1PcWl2N4tWdnnk5E8e0l4s5h4NGS1251305030305 月cker psstreamlit 運行Genapp.pygit m 克隆https:/ / github。 com/ ID/Es/alat/Foneed/Fidal） ip install -r requests.txtsource ~/.bash rcconda 啟動multimodal-ragcd multimodal - rag/txtsource ~/.bashrcconda 啟動multimodal-ragcd multumods vIKPx12HvHynY* mleiISz-9e&quot;sudo Park塢窗</pre><ol><li>在 Web 瀏覽器中打開提供的 URL。</li><li>選擇上傳檔或指定包含文件的目錄路徑。</li><li>通過單擊「處理檔」或「處理目錄」 按鈕來處理檔。</li><li>處理完成後，使用聊天介面查詢您的文件。</li></ol><h3>檔結構</h3><ul><li>app.py： 設置Streamlit 頁面並管理多式聯運RAG系統</li><li>document_processors.py：用於處理各種文件類型的函數(如PDF、Powerpoint、影像)</li></ul><ol><li>def get_pdf_documents(pdf_file):Process a PDF file and extract text, tables, and images.</li></ol><p>2. def parse_all_tables(filename, page, pagenum, text_blocks, ongoing_tables):Extract tables from a PDF page.</p><p>3. def parse_all_images(filename, page, pagenum, text_blocks):Extract images from a PDF page.</p><p>4. def process_ppt_file(ppt_path):Process a PowerPoint file.</p><p>5. def convert_ppt_to_pdf(ppt_path):Convert a PowerPoint file to PDF using LibreOffice.</p><p>6. def convert_pdf_to_images(pdf_path):Convert a PDF file to a series of images using PyMuPDF.</p><p>7. def extract_text_and_notes_from_ppt(ppt_path):Extract text and notes from a PowerPoint file.</p><p>8. def load_multimodal_data(files):Load and process multiple file types.</p><p>9. def load_data_from_directory(directory):Load and process multiple file types from a directory.</p><ul><li>utils.py：用於圖像處理和 API 交互、文本處理的函數</li></ul><p>Set necessary environment variables<br>Convert image content to base64 encoded string<br>Determine if an image is a graph, plot, chart, or table<br>Process a graph image and generate a description(llama-3.1-8b)<br>Generate a description of an image using NVIDIA API(neva-22b)<br>Process a graph image using NVIDIA’s Deplot API<br>Extract text above and below a given bounding box on a page<br>Group text blocks based on a character count threshold<br>Save an uploaded file to a temporary directory</p><ul><li>requirements.txt:P ython 依賴項清單</li><li>vectorstore/：用於存儲 pdf 和ppt中資訊的儲存庫，其下有<br> image_references 和 ppt_references 兩個資料夾</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*DO1tk9OdSSSWyUg_GK5WaA.png" /></figure><h3>用於向量搜索的 GPU 加速</h3><p>要在向量資料庫中使用 GPU 加速，請確保：</p><ol><li>您的系統具有相容的 NVIDIA GPU。</li><li>你正在使用支援 GPU 的 Milvus 版本（如設置說明所示）。</li><li>有足夠的併發請求來證明 GPU 使用的合理性。GPU 加速通常在高負載條件下顯示出顯著的優勢。</li></ol><p>請務必注意，僅當傳入請求非常高時，才會使用 GPU 加速。有關 Milvus 中 GPU 索引和搜索的更多詳細資訊，請參閱 <a href="https://milvus.io/docs/gpu_index.md">Milvus GPU 索引官方文檔</a>。</p><p>要將 GPU 加速的 Milvus 與 LlamaIndex 連接起來，請在 app.py 中更新 MilvusVectorStore 配置：</p><pre>vector_store = MilvusVectorStore(<br>    host=&quot;127.0.0.1&quot;,<br>    port=19530,<br>    dim=1024,<br>    collection_name=&quot;your_collection_name&quot;,<br>    gpu_id=0  # Specify the GPU ID to use<br>)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=469930d6fa68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Finetuning framework and resources]]></title>
            <link>https://medium.com/@ethankuo_74456/llm-finetuning-framework-and-resources-219dcbc0ec1c?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/219dcbc0ec1c</guid>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 03:48:05 GMT</pubDate>
            <atom:updated>2024-11-27T03:48:05.089Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>一、 LlamaFactory</strong></p><p>LLaMA-Factory 這個專案提供了一個方便的 WebUI 介面，並且整合了各種常見的訓練方式，讓使用者可以方便的調整參數便開始微調屬於自己的語言模型。點此見<a href="https://github.com/hiyouga/LLaMA-Factory">Github專案</a>，關於不同訓練方式見此<a href="https://medium.com/p/bc806eddce0f/edit">medium文章</a></p><p><strong>1.1 在Colab中開啟 LlamaFactory 的 UI 介面</strong></p><p><a href="https://colab.research.google.com/github/ADT109119/LLaMA-Factory-Colab/blob/main/LLaMA-Factory-Colab.ipynb#scrollTo=7RomxmJkjnqE">LLaMA-Factory-Colab.ipynb — Colab</a></p><p><strong>1.2 在本機安裝LlamaFactory</strong></p><p><a href="https://medium.com/r?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtihBvGnAuzw">Youtube 安裝教學</a></p><pre># 建立 conda 指定 Python 版本<br>conda create -n LLaMA-Factory python=3.12<br>conda activate LLaMA-Factory</pre><pre>git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git<br>cd LLaMA-Factory<br>pip install -e &quot;.[torch,metrics]&quot;<br>pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.2.post2-py3-none-win_amd64.whl</pre><pre># OSError: [WinError 126] 找不到指定的模組。 Error loading &quot;~\LLaMA-Factory\Lib\site-packages\torch\lib\fbgemm.dll&quot; or one of its dependencies.<br># 改安裝torch 2.3.0 版<br>pip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0</pre><p>如果有 GPU 需要加速請安裝 Cuda 12.1以上及相關套件</p><pre># cuda 12.1<br># cuda 下載網址: https://developer.nvidia.com/cuda-12-1-0-download-archive<br>pip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 --index-url https://download.pytorch.org/whl/cu121<br><br># cuda 12.4<br># cuda 下載網址: https://developer.nvidia.com/cuda-12-4-0-download-archive<br>pip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 --index-url https://download.pytorch.org/whl/cu124# cuda 12.1# cuda 下載網址: https://developer.nvidia.com/cuda-12-1-0-download-archivepip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 --index-url https://download.pytorch.org/whl/cu121# cuda 12.4# cuda 下載網址: https://developer.nvidia.com/cuda-12-4-0-download-archivepip install torch==2.3.0 torchvision==0.18.0 torchaudio==2.3.0 --index-url https://download.pytorch.org/whl/cu124</pre><p>介面繁體中文化，將下面檔案覆蓋後即可繁體中文化</p><p>路徑： ~\LLaMA-Factory\src\llamafactory\webui</p><pre>開啟UI介面<br>llamafactory-cli webui開啟UI介面llamafactory-cli webui</pre><p><strong>二、 Unsloth</strong></p><p>Unsloth 是一個專為大型語言模型（LLMs）微調設計的高效開源框架，旨在簡化流程並降低資源需求。它支援 LoRA 等技術，可在有限硬體資源下完成高效微調，並內建多種工具支援提示工程（Prompt-Tuning）與檢索強化生成（RAG）。Unsloth 提供便捷的模型格式轉換，支持本地化部署（如 GGUF 格式和 LM Studio），非常適合個性化微調與快速原型開發。其模組化設計和強大擴展性，使其成為研究和產業應用中處理 LLM 微調的理想選擇，唯一可惜的是目前並<strong>不支援多GPU訓練</strong>。<a href="https://github.com/unslothai/unsloth">點此見Github專案</a>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*h55I6HOAq4zoZOaWdC1MGw.png" /></figure><p><strong>2.1 在Colab 中使用Unsloth 框架<br></strong>參閱<a href="https://colab.research.google.com/drive/1BEuW9yRV_1bvuZLDGPEQ4XS5OLDNkILH?authuser=1#scrollTo=LjY75GoYUCB8">Fine_Tuning_unsloth.ipynb — Colab</a> ，除此之外也可以參考<a href="https://huggingface.co/unsloth">unsloth (Unsloth AI)</a>關於其他模型的微調程式碼。</p><p><strong>2.2 地端環境安裝Unsloth<br></strong>安裝影片 : <a href="https://www.youtube.com/watch?v=ZQIPnSiiwKw">Unsloth + Llama 3</a></p><p><strong>三、 Github專案<br></strong>一個適用於大型語言模型的 Gradio Web UI ，它的目標是成為文本生成的 <a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui">AUTOMATIC1111/stable-diffusion-webui</a>，功能是目前看到最齊全的</p><p><strong>3.1 在Colab 中開啟微調的UI介面</strong></p><p><a href="https://colab.research.google.com/github/oobabooga/text-generation-webui/blob/main/Colab-TextGen-GPU.ipynb#scrollTo=LGQ8BiMuXMDG">Colab-TextGen-GPU.ipynb — Colab</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLPT3ie1IHKd7JkdGBoWJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jC7VMQVSprFFAjghdrYggQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqA5CFO7zWtvoiniCBA3Pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_EY5OYbEkhtE_ZQQJRgpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TrYs4tuegWfOj97EerKX_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KapZid0rwW0FmFVvTgT_0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RjVGLbcJQt0uwWBPiE70w.png" /></figure><p><strong>4. NVIDIA NeMo</strong></p><p>需要安裝NeMo Container - <a href="https://catalog.ngc.nvidia.com/orgs/nvidia/containers/nemo/tags">NeMo Docker 各版本連結</a></p><p>參閱<a href="https://github.com/j3soon/LLM-Tutorial">國網中心的教材</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=219dcbc0ec1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用 Unsloth 框架微調 LLaMA 3.1 8B 模型：從 Colab 訓練到本地 GGUF 模型部署與 Streamlit 推論]]></title>
            <link>https://medium.com/@ethankuo_74456/%E4%BD%BF%E7%94%A8-unsloth-%E6%A1%86%E6%9E%B6-finetune-llama-3-1-8b-%E6%A8%A1%E5%9E%8B-%E4%B8%A6%E4%B8%8B%E8%BC%89-gguf-%E6%A8%A1%E5%9E%8B%E6%AA%94%E6%96%BC%E6%9C%AC%E6%A9%9F%E6%8E%A8%E8%AB%96-colab-abb3a8b2828f?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/abb3a8b2828f</guid>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:52:57 GMT</pubDate>
            <atom:updated>2024-11-12T09:17:38.809Z</atom:updated>
            <content:encoded><![CDATA[<p>Fine-Tuning LLaMA 3.1 8B with Unsloth: From Colab Training to Local GGUF Deployment with Streamlit Inference</p><p><strong>前言</strong><br>本文介紹如何使用Google Colab 運用開源框架Unsloth 微調Llama3.1 8B模型，並將模型轉換儲存為gguf檔案後下載，利用本機端安裝的LM Studio軟體做模型推論，並且提供Github 聊天機器人的專案，在本機端安裝後開啟LM Studio的Server，即可在本機端部署有Streamlit 互動介面的RAG Chatbot。</p><p>This article introduces how to use Google Colab to fine-tune the Llama 3.1 8B model with the open-source framework Unsloth. After fine-tuning, the model is converted and saved as a GGUF file for download. The local LM Studio software is then used for model inference. Additionally, the project provides a GitHub-based chatbot. By installing it locally and enabling the LM Studio server, you can deploy an RAG chatbot with a Streamlit interactive interface on your local machine.</p><h3>Part 1 — 在Unsloth 框架下微調 Llama 3.1 8B 模型</h3><p>Unsloth 是一個專為大型語言模型（LLMs）微調設計的高效開源框架，旨在簡化流程並降低資源需求。它支援 LoRA 等技術，可在有限硬體資源下完成高效微調，並內建多種工具支援提示工程（Prompt-Tuning）與檢索強化生成（RAG）。此外，Unsloth 提供便捷的模型格式轉換，支持本地化部署（如 GGUF 格式和 LM Studio），非常適合個性化微調與快速原型開發。其模組化設計和強大擴展性，使其成為研究和產業應用中處理 LLM 微調的理想選擇，唯一可惜的是目前並不支援多GPU訓練。</p><p>關於本篇所使用Unsloth框架的資源，參閱 <a href="https://colab.research.google.com/drive/1BEuW9yRV_1bvuZLDGPEQ4XS5OLDNkILH?authuser=1#scrollTo=LjY75GoYUCB8">Fine_Tuning_unsloth.ipynb — Colab</a>，除此之外也可以參考<a href="https://huggingface.co/unsloth">unsloth (Unsloth AI)</a>關於其他模型的微調程式碼。</p><p><strong>1.1 Load the model:</strong></p><p>Unsloth 框架提供多個優化後的模型讓我們微調，唯一較可惜的部分是目前並不支援多GPU訓練，如果要在colab的記憶體資源下完整訓練並下載gguf模型檔，筆者嘗試 Llama-3.1–8B-Instruct-bnb-4bit 可行，或著也可以嘗試訓練Llama3.1 1B或3B的模型</p><pre>from unsloth import FastLanguageModel<br>import torch<br><br>max_seq_length = 2048    # 模型在處理輸入序列時的最大長度，在此可選擇任何數值！因為Unsloth內部透過 kaiokendev 的方法自動進行 RoPE 擴展<br>dtype = None         # None 表示自動檢測。對於 Tesla T4、V100 使用 Float16，對於 Ampere+ 使用 Bfloat16<br>load_in_4bit = True      # 使用 4bit 量化以減少內存使用。可以設置為 False。<br><br># Unsloth 支援的 4bit 預量化模型，下載速度加快 4 倍且無記憶體不足問題。<br>fourbit_models = [<br>    &quot;unsloth/Meta-Llama-3.1-8B-bnb-4bit&quot;,      # Llama-3.1，15 兆億個參數模型，速度加快 2 倍<br>    &quot;unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit&quot;,<br>    &quot;unsloth/Meta-Llama-3.1-70B-bnb-4bit&quot;,<br>    &quot;unsloth/Meta-Llama-3.1-405B-bnb-4bit&quot;,     # Llama-3.1， 405B 的 4bit 版本<br>    &quot;unsloth/Mistral-Nemo-Base-2407-bnb-4bit&quot;,<br>    &quot;unsloth/Mistral-Nemo-Instruct-2407-bnb-4bit&quot;,<br>    &quot;unsloth/mistral-7b-v0.3-bnb-4bit&quot;,<br>    &quot;unsloth/mistral-7b-instruct-v0.3-bnb-4bit&quot;,<br>    &quot;unsloth/Phi-3.5-mini-instruct&quot;,<br>    &quot;unsloth/Phi-3-medium-4k-instruct&quot;,<br>    &quot;unsloth/gemma-2-9b-bnb-4bit&quot;,<br>    &quot;unsloth/gemma-2-27b-bnb-4bit&quot;,<br><br>    &quot;unsloth/Llama-3.2-1B-bnb-4bit&quot;,           # NEW! Llama 3.2 models<br>    &quot;unsloth/Llama-3.2-1B-Instruct-bnb-4bit&quot;,<br>    &quot;unsloth/Llama-3.2-3B-bnb-4bit&quot;,<br>    &quot;unsloth/Llama-3.2-3B-Instruct-bnb-4bit&quot;,<br>]  # 更多模型可以參考 https://huggingface.co/unsloth<br><br># 使用 FastLanguageModel 從預訓練模型加載模型和 tokenizer<br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit&quot;,   # 指定要加載的模型名稱<br>    max_seq_length = max_seq_length,           # 設定最大序列長度<br>    dtype = dtype,                     # 設定數據類型<br>    load_in_4bit = load_in_4bit,              # 設定是否使用 4bit 量化<br>    # token = &quot;hf_...&quot;,  # 如果使用需要許可的模型，例如 meta-llama/Llama-2-7b-hf，可以在這裡設置token<br>)</pre><p><strong>1.2 Data Preprocessing:</strong><br><a href="https://huggingface.co/datasets/yahma/alpaca-cleaned?row=22">yahma/alpaca-cleaned · Datasets at Hugging Face</a>1.1 資料預處理：yahma/alpaca-cleaned · Hugging Face資料集</p><p>本範例使用來自 yahma 的 Alpaca 資料集，這是一個過濾版本，包含了原始 [<a href="https://crfm.stanford.edu/2023/03/13/alpaca.html">Alpaca 資料集</a>] 的 52K 筆資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*292Dd41hF73RwbcehCuz9Q.png" /></figure><p>程式中資料前處理的程式碼，主要目的是準備和格式化 Alpaca 數據集，以便用於模型訓練，並確保在輸出中加入了 EOS_TOKEN（結束標記），防止生成過程無限延續。如果您對資料前處理有困擾，也可以選擇運用資料前處理的軟體工具</p><pre>#定義一個模板字串 alpaca_prompt，用於格式化 Prompt。該模板包含 Instruction、Input 和 Response 三個部分：<br>#Instruction 提供了任務說明，Input 提供了上下文，Response 是語言模型應生成的回應<br>#使用 {} 作為佔位符，以便在格式化時插入具體的指令、輸入內容和回應。<br><br>alpaca_prompt = &quot;&quot;&quot;Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.<br><br>### Instruction:<br>{}<br><br>### Input:<br>{}<br><br>### Response:<br>{}&quot;&quot;&quot;<br><br><br><br>#使用 tokenizer.eos_token 取得特殊的 &quot;結束&quot;（End-of-Sequence, EOS）標記，確保生成的句子在適當的地方終止。這對於防止模型生成無限長的回應非常重要<br>EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN<br><br><br>#formatting_prompts_func 函數，該函數將資料集中的每個樣本格式化為 Alpaca Prompt 模板<br>def formatting_prompts_func(examples):<br>    instructions = examples[&quot;instruction&quot;]<br>    inputs       = examples[&quot;input&quot;]<br>    outputs      = examples[&quot;output&quot;]<br>    texts = []<br>    for instruction, input, output in zip(instructions, inputs, outputs):<br>        # Must add EOS_TOKEN, otherwise your generation will go on forever!<br>        text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN<br>        texts.append(text)<br>    return { &quot;text&quot; : texts, }<br>pass<br><br><br>#下載資料集並應用格式化函數<br>from datasets import load_dataset<br>dataset = load_dataset(&quot;yahma/alpaca-cleaned&quot;, split = &quot;train&quot;)<br>dataset = dataset.map(formatting_prompts_func, batched = True,)#定義了一個模板字串 alpaca_prompt，用於格式化 Prompt。該模板包含 Instruction、Input 和 Response 三個部分：#Instruction 提供了任務說明，Input 提供了上下文，Response 是語言模型應生成的回應#使用 {} 作為佔位符，以便在格式化時插入具體的指令、輸入內容和回應。alpaca_prompt = &quot;&quot;&quot;Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.### Instruction:{}### Input:{}### Response:{}&quot;&quot;&quot;#使用 tokenizer.eos_token 取得特殊的 &quot;結束&quot;（End-of-Sequence, EOS）標記，確保生成的句子在適當的地方終止。這對於防止模型生成無限長的回應非常重要EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN#formatting_prompts_func 函數，該函數將資料集中的每個樣本格式化為 Alpaca Prompt 模板def formatting_prompts_func(examples):    instructions = examples[&quot;instruction&quot;]    inputs       = examples[&quot;input&quot;]    outputs      = examples[&quot;output&quot;]    texts = []    for instruction, input, output in zip(instructions, inputs, outputs):        # Must add EOS_TOKEN, otherwise your generation will go on forever!        text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN        texts.append(text)    return { &quot;text&quot; : texts, }pass#下載資料集並應用格式化函數from datasets import load_datasetdataset = load_dataset(&quot;yahma/alpaca-cleaned&quot;, split = &quot;train&quot;)dataset = dataset.map(formatting_prompts_func, batched = True,)</pre><p><strong>1.3 Train the model:</strong></p><p>使用 Huggingface TRL 的 SFTTrainer訓練模型，相關文件請參考<a href="https://huggingface.co/docs/trl/sft_trainer">TRL SFT 文件</a>。我們設定 max_steps = 2 以較快看到微調結果與節省記憶體，您可以設定num_train_epochs = 1以進行完整的一個epoch訓練運行(同時並設定max_steps=None)。</p><pre>from trl import SFTTrainer<br>from transformers import TrainingArguments, DataCollatorForSeq2Seq<br>from unsloth import is_bfloat16_supported<br><br>trainer = SFTTrainer(<br>    model = model,<br>    tokenizer = tokenizer,<br>    train_dataset = dataset,<br>    dataset_text_field = &quot;text&quot;,<br>    max_seq_length = max_seq_length,<br>    data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer),<br>    dataset_num_proc = 2,<br>    packing = False, # Can make training 5x faster for short sequences.<br>    args = TrainingArguments(<br>        per_device_train_batch_size = 2,<br>        gradient_accumulation_steps = 4,<br>        warmup_steps = 5,<br>        # num_train_epochs = 1, # Set this for 1 full training run.<br>        max_steps = 60,<br>        learning_rate = 2e-4,<br>        fp16 = not is_bfloat16_supported(),<br>        bf16 = is_bfloat16_supported(),<br>        logging_steps = 1,<br>        optim = &quot;adamw_8bit&quot;,<br>        weight_decay = 0.01,<br>        lr_scheduler_type = &quot;linear&quot;,<br>        seed = 3407,<br>        output_dir = &quot;outputs&quot;,<br>        report_to = &quot;none&quot;, # Use this for WandB etc<br>    ),<br>)</pre><p><strong>1.4 Inference</strong></p><pre># alpaca_prompt = Copied from above<br>FastLanguageModel.for_inference(model) # Enable native 2x faster inference<br>inputs = tokenizer(<br>[<br>    alpaca_prompt.format(<br>        &quot;Continue the fibonnaci sequence.&quot;, # instruction<br>        &quot;1, 1, 2, 3, 5, 8&quot;, # input<br>        &quot;&quot;, # output - leave this blank for generation!<br>    )<br>], return_tensors = &quot;pt&quot;).to(&quot;cuda&quot;)<br><br>outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True, pad_token_id = tokenizer.eos_token_id)<br>tokenizer.batch_decode(outputs)</pre><p><strong>參數解釋：</strong></p><p>**inputs：</p><ul><li>將前面生成的編碼張量作為輸入。</li></ul><p>max_new_tokens = 64：</p><ul><li>限制生成的 token 數量最多為 64，以避免生成過多內容。</li></ul><p>use_cache = True：</p><ul><li>啟用快取機制，儲存中間結果來提升計算效率。</li></ul><p>pad_token_id = tokenizer.eos_token_id：</p><ul><li>設定填充的 token 為模型的結束 token ID，確保生成過程正確處理 padding（填充）。</li></ul><p><strong>1.5 Save LoRA Adaper</strong></p><pre>model.save_pretrained(&quot;lora_model&quot;) # Local saving<br>tokenizer.save_pretrained(&quot;lora_model&quot;)<br># model.push_to_hub(&quot;your_name/lora_model&quot;, token = &quot;...&quot;) # Online saving<br># tokenizer.push_to_hub(&quot;your_name/lora_model&quot;, token = &quot;...&quot;) # Online savingmodel.save_pretrained(&quot;lora_model&quot;) # 本地儲存tokenizer.save_pretrained(&quot;lora_model&quot;)# model.push_to_hub(&quot;your_name/lora_model&quot;, token = &quot;...&quot;) # 線上儲存 tokenizer.push_hufhuname( &quot; , token = &quot;...&quot;) # 線上儲存</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*pM0TvH1Rk1sFmJDAVoOmmQ.png" /></figure><p><strong>1.6 Load LoRA Adaper</strong></p><p>如果想載入我們剛剛保存的 LoRA Adaper進行模型推論，將 False 設定為 True (但在此可能會有Colab VRAM不足的問題，視你的記憶體用量而定)</p><pre>if True:<br>    from unsloth import FastLanguageModel<br>    model, tokenizer = FastLanguageModel.from_pretrained(<br>        model_name = &quot;lora_model&quot;, # YOUR MODEL YOU USED FOR TRAINING<br>        max_seq_length = max_seq_length,<br>        dtype = dtype,<br>        load_in_4bit = load_in_4bit,<br>    )<br>    FastLanguageModel.for_inference(model) # Enable native 2x faster inference<br><br># alpaca_prompt = You MUST copy from above!<br><br>inputs = tokenizer(<br>[<br>    alpaca_prompt.format(<br>        &quot;What is a famous tall tower in Paris?&quot;, # instruction<br>        &quot;&quot;, # input<br>        &quot;&quot;, # output - leave this blank for generation!<br>    )<br>], return_tensors = &quot;pt&quot;).to(&quot;cuda&quot;)<br><br>from transformers import TextStreamer<br>text_streamer = TextStreamer(tokenizer, skip_prompt = True)<br>_ = model.generate(input_ids = inputs.input_ids, attention_mask = inputs.attention_mask,<br>                   streamer = text_streamer, max_new_tokens = 64, pad_token_id = tokenizer.eos_token_id)</pre><p><strong>1.7 儲存為GGUF格式</strong></p><p>如果想要將模型檔儲存為 GGUF / llama.cpp格式，可以使用以下程式:</p><p>a. 使用 save_pretrained_gguf 將模型存成GGUF檔，下載到有足夠硬體資源的本機端搭配有UI介面的軟體(如LM Studio)做模型推論</p><p>b. 使用 push_to_hub_gguf 將模型檔上傳到 Hugging Face。</p><p>在此我們下載q4_k_m GGUF的格式儲存</p><pre># Save to 8bit Q8_0<br>if False: model.save_pretrained_gguf(&quot;model&quot;, tokenizer,)<br># Remember to go to https://huggingface.co/settings/tokens for a token!<br># And change hf to your username<br>if False: model.push_to_hub_gguf(&quot;hf/model&quot;, tokenizer, token = &quot;&quot;)<br><br># Save to 16bit GGUF<br>if False: model.save_pretrained_gguf(&quot;model&quot;, tokenizer, quantization_method = &quot;f16&quot;)<br>if False: model.push_to_hub_gguf(&quot;hf/model&quot;, tokenizer, quantization_method = &quot;f16&quot;, token = &quot;&quot;)<br><br># Save to q4_k_m GGUF<br>if True: model.save_pretrained_gguf(&quot;model&quot;, tokenizer, quantization_method = &quot;q4_k_m&quot;)<br>if False: model.push_to_hub_gguf(&quot;hf/model&quot;, tokenizer, quantization_method = &quot;q4_k_m&quot;, token = &quot;&quot;)<br><br># Save to multiple GGUF options - much faster if you want multiple!<br>if False:<br>    model.push_to_hub_gguf(<br>        &quot;hf/model&quot;, # Change hf to your username!<br>        tokenizer,<br>        quantization_method = [&quot;q4_k_m&quot;, &quot;q8_0&quot;, &quot;q5_k_m&quot;,],<br>        token = &quot;&quot;, # Get a token at https://huggingface.co/settings/tokens<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*Z9vESx5pvr-dFvjoDAGkeg.png" /></figure><p>安裝llama.cpp並將模型轉換為FP16的gguf格式，會逐次將pytorch_model-00001~00004.bin做轉換</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*_aNibmxaZ3Dtz7NjchCbhA.png" /></figure><p>設定模型參數</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*RLTw5YspPOWuP9UvTALAnQ.png" /></figure><p>設定model tokenizer設定model tokenizer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*IMv_vY0N4DUHBeeiKQIz5g.png" /></figure><p>再將FP16 gguf 的模型轉換為 q4_k_m</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wp2h--4Uur2Ska-svvZQNg.png" /></figure><p>我們可以看到每一層轉換後占用的記憶體空間</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yo8HgB6rL1jmxQBaAJhFqw.png" /></figure><p>最後轉換完成的資訊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*kJo-rh8b6HY3SJe3OK7S_w.png" /></figure><p>完成後可以下載unsloth.Q4_K_M.gguf 的模型</p><h3>Part 2 — 在LM Studio 中進行微調後的模型推論</h3><p><strong>2.1 </strong><a href="https://lmstudio.ai/"><strong>下載 LM Studio</strong></a><strong> 後，找到模型檔存放的路徑，並加入自己微調後的模型</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-02t3osPknml4oyt1ArHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*7_x4bBslnoVpfc0N5uQ5HA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*mXjMHLyHdBVZrsCueY3YiQ.png" /></figure><p><strong>2.2 在LM Studio 中測試 finetuned 後的 Llama 3.1 8B 模型</strong></p><p>測試 :我們詢問在Finetune dataset中的數學問題，這題牽涉到數學的排列組合</p><p>Question : The Happy Valley Kennel has 4 chickens, 2 dogs, and 5 cats. (Some people in Happy Valley like to keep chickens as pets!) In how many ways can the 11 animals be placed in a row of 11 cages, such that all of the animals of each type are in adjacent cages? (Two animals of the same species are considered distinguishable.)</p><p>問題: 跑馬地狗舍有4隻雞、2隻狗和5隻貓。 （跑馬地有些人喜歡養雞當寵物！） 有多少種方法可以將 11 隻動物放在一排 11 個籠子裡，使每種動物都在相鄰的籠子裡？ （同一物種的兩種動物被認為是可以區分的。）</p><p>以下是微調後模型的回應，有正確的解出這個數學問題的答案</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*DYFKY6yty20udThJrLyPhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*7K_A1AJY7KCPB6JzHN-Bww.png" /></figure><h3>Part 3 — 搭配UI介面進行本機端檢索問答</h3><h4>3.1 在本機端建立有Streamlit頁面的聊天機器人</h4><p>關於在本機端安裝環境與啟用RAG聊天機器人，可以參考這一篇文章的說明:</p><p><a href="https://medium.com/@ethankuo_74456/local-rag-chatbot-open-source-llm-ca3d4a873ad9">Local RAG Chatbot with streamlit interface (open source LLM) | by Ethan Kuo | Oct, 2024 | Medium</a></p><p><strong>3.2 開啟LM Studio 的 server，並選取剛剛手動加入的llama3.1 8B模型</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSn2fRd4pWT0aIC_UOpRJg.png" /></figure><p><strong>3.3 實測RAG結果</strong></p><p>以下是Llama 3.1 8B 模型實測RAG Chatbot的結果:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ucyff8L5xPeZpa-pXNNXrg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abb3a8b2828f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local RAG Chatbot with streamlit interface (open source LLM)]]></title>
            <link>https://medium.com/@ethankuo_74456/local-rag-chatbot-open-source-llm-ca3d4a873ad9?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca3d4a873ad9</guid>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 15:27:26 GMT</pubDate>
            <atom:updated>2024-10-20T11:35:47.978Z</atom:updated>
            <content:encoded><![CDATA[<p>This step-by-step guide will help you set up a Retrieval-Augmented Generation (RAG) chatbot on your local machine. Even if you’re a beginner, follow these instructions carefully, and you should be able to get your chatbot running. Additional explanations are provided where necessary.</p><h3>The UI interface during execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*EcomcynweMtU6DM2xIdUGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*nx8k2gWN2o2-F-Uu_Bd8rQ.png" /></figure><h3>Setting Up a Local RAG Chatbot Environment</h3><h4>1. Install Anaconda3</h4><p>You will need Anaconda or Miniconda to manage the Python environment for the chatbot. Choose one of the options below:</p><ul><li><strong>Anaconda</strong>: Sign up with your email and download Anaconda from the link sent to you. Download it from <a href="https://www.anaconda.com/download">here</a>.</li><li><strong>Miniconda</strong>: A lightweight version of Anaconda. Download it from <a href="https://docs.anaconda.com/miniconda/">here</a>.</li></ul><h4>2. Create a Folder for the Chatbot</h4><ul><li>On your desktop, create a folder called <strong>chatbot</strong>. This will be where you store the project files.</li></ul><h4>3. Open Anaconda Powershell Prompt</h4><ul><li>After installing Anaconda or Miniconda, open the <strong>Anaconda Powershell Prompt</strong> to enter commands.</li></ul><h4>4. Set Up the Python Environment</h4><ul><li>In the Anaconda Powershell Prompt, type the following commands to create and activate a new Python environment:</li></ul><pre>conda create -n chatbot python=3.10 <br><br>conda activate chatbot</pre><h4>5. Navigate to the Chatbot Folder</h4><ul><li>Use the cd command to navigate to the folder you created on your desktop. Replace the path below with the actual path to your folder:</li></ul><pre>cd C:\Users\ison0\OneDrive\Desktop\chatbot</pre><p><strong>Tip</strong>: Make sure to replace the path C:\Users\ison0\OneDrive\Desktop\chatbot with your own folder path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*s3VJKm9BLJwaIr0cD5y8Yg.png" /></figure><h4>6. Clone the RAG Chatbot Repository and Install Dependencies</h4><ul><li>In the Anaconda Powershell Prompt, clone the GitHub repository and install the necessary Python packages:</li></ul><pre>git clone https://github.com/trombone1/LangChain-RAG-Chatbot.git <br><br>cd LangChain-RAG-Chatbot\RAG-Based-Chatbot <br><br>pip install -r requirements.txt</pre><h4>7. Get an API Key from Cohere</h4><ul><li>Go to <a href="https://dashboard.cohere.com/">Cohere Dashboard</a> and sign up for an API key. This key will be needed to connect to Cohere’s language models.The reason you need to apply for an API key is that the project utilizes Cohere’s rerank model.</li></ul><h4>8. Insert the API Key into the Falcon Script</h4><ul><li>Open the falcon.py file located in the project folder. At <strong>line 17</strong>, paste your Cohere API key like this:</li></ul><pre>cohere_api_key = &quot;your_cohere_api_key_here&quot;</pre><ul><li>Save the file after pasting your key.</li></ul><h4>9. Insert the Hugging Face Token into the Streamlit Script</h4><ul><li>Open the chatbot_streamlit_combined.py file. At <strong>line 16</strong>, paste your Hugging Face token like this:</li></ul><pre>token = &quot;your_huggingface_token_here&quot;</pre><ul><li>Save the file after pasting your token.</li></ul><h4>10. Inatall and Start LM Studio</h4><ul><li>If you want to use your own computer’s processing power to run the downloaded LLM model, you can install the software called LM Studio.</li><li>For instructions on how to use LM Studio, you can refer to this tutorial video: <a href="https://www.youtube.com/watch?v=SUeIsSML2UY">https://www.youtube.com/watch?v=SUeIsSML2UY</a></li><li>Open <strong>LM Studio</strong>, choose the appropriate conversational model, and start the server. This will allow the chatbot to process inputs and generate responses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8biuZ_3KFd1rbodUQQMQYA.png" /></figure><p>In the falcon.py code, line 98 is where the connection to the local model provided by LM Studio is made. If you comment out the base_url and replace the token with your OpenAI API key, you can use OpenAI&#39;s cloud-based model instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*6JNNb_9DLTiU33jeWd8wyA.png" /></figure><h4>11. Run the Chatbot</h4><ul><li>In the Anaconda Powershell Prompt, run the following command to launch the chatbot with <strong>Streamlit</strong>:</li></ul><pre>streamlit run chatbot_streamlit_combined.py</pre><h4>12. Running the Chatbot in the Future</h4><ul><li>Anytime you want to start the chatbot again, follow these steps:</li></ul><ol><li>Activate the Python environment:</li></ol><pre>conda activate chatbot</pre><p>2. Navigate to the chatbot folder:</p><pre>cd C:\Users\ison0\OneDrive\Desktop\chatbot\LangChain-RAG-Chatbot\RAG-Based-Chatbot</pre><p>3. Run the Streamlit command:</p><pre>streamlit run chatbot_streamlit_combined.py</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca3d4a873ad9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[NVIDIA 開發百寶箱]-手把手帶你運用NVIDIA NIM 微服務建立結構化CSV資料查詢助理]]></title>
            <link>https://medium.com/@ethankuo_74456/nvidia-%E9%96%8B%E7%99%BC%E7%99%BE%E5%AF%B6%E7%AE%B1-%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%B6%E4%BD%A0%E9%81%8B%E7%94%A8nvidia-nim-%E5%BE%AE%E6%9C%8D%E5%8B%99%E5%BB%BA%E7%AB%8B%E7%B5%90%E6%A7%8B%E5%8C%96csv%E8%B3%87%E6%96%99%E6%9F%A5%E8%A9%A2%E5%8A%A9%E7%90%86-c607cc43e851?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/c607cc43e851</guid>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 14:11:52 GMT</pubDate>
            <atom:updated>2026-04-06T14:44:51.838Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>本文為筆者於 2024 Data Science Meetup 分享部分內容，主題: LLM 於結構化CSV資料之檢索應用 (2024/7/11) , </strong><a href="https://drive.google.com/file/d/1NN2kQsTbOiQ1_hnXQf3oOtLpESPpFb2W/view?usp=drive_link"><strong>點此</strong></a><strong>見當日分享投影片連結</strong></p><p>This article is based on part of the author’s presentation at the 2024 Data Science Meetup. The topic was <strong>“Applications of LLMs for Retrieving Information from Structured CSV Data”</strong> (July 11, 2024). Click <a href="https://drive.google.com/file/d/1NN2kQsTbOiQ1_hnXQf3oOtLpESPpFb2W/view">here</a> to view the presentation slides from that session.</p><h3>前言</h3><p>當前生成式 AI 快速發展的時代下，資料科學實作正迎來許多創新應用和解決方案。即便是不會寫程式的人，也能夠運用生成式 AI 來執行資料科學任務。本篇文章將帶大家使用日常語言對結構化資料實現資料查詢與統計量問答:一個整合Pandas AI Agent與NVIDIA NIM 微服務的資料檢索方案，並附上實作流程教學。</p><p>這是NVIDIA GenerativeAIExamples 其中一個<a href="https://nvidia.github.io/GenerativeAIExamples/latest/structured-data.html#example-features">例子</a>，展示了如何將大型語言模型結合結構化的CSV資料進行RAG（Retrieval-Augmented Generation），特別的是僅使用PandasAI來管理整個工作流程，沒有使用embedding model和vector database。</p><p>使用 PandasAI Agent 從 DataFrame 中提取訊息，首先將使用者的Query與DataFrame的結構結合，形成一個LLM prompt。然後，LLM生成Python代碼以從DataFrame中提取所需訊息。隨後，這些生成的代碼在DataFrame上執行，並產生輸出資料框。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96qRsaKZ3LPtK7_uhnLn7w.png" /><figcaption>範例聊天機器人 Web 應用程式與chain server進行通訊。chain server將推理請求傳送到 NVIDIA API Catalog endpoint</figcaption></figure><h3>一、安裝 WSL2 Ubuntu-22.04</h3><p>WSL2（Windows Subsystem for Linux Version 2）是開發人員在 Windows 環境中使用 Linux 的理想選擇，其提供了一個完整的 Linux 內核直接在 Windows 中運行，從而實現了優化的文件系統性能和更高的系統調用兼容性。它允許無需雙重啟動或設置傳統虛擬機就能高效地運行 Linux 環境，並支持 Linux 圖形應用程序及 GPU 加速。</p><pre>wsl --unregister Ubuntu-22.04<br>wsl --install -d Ubuntu-22.04<br>wsl --update</pre><h4>1.1 開始安裝套件</h4><p>首先更新 Ubuntu 當中的套件，並將已經安裝的套件升級到最新版本。</p><pre>sudo apt-get update<br>sudo apt-get upgrade</pre><h4>1.2 下載GenerativeAIExamples</h4><pre>git clone https://github.com/NVIDIA/GenerativeAIExamples.git<br>cd GenerativeAIExamples</pre><h4>1.3 申請APIKEY</h4><p>使用開發者帳號，到<a href="https://org.ngc.nvidia.com/setup/personal-keys">org.ngc.nvidia.com/setup/personal-keys</a> 網站申請API Key，可得到1000 credict的使用額度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*KAMwVswUFQwTtKzfS6lQEA.png" /></figure><h4>1.4 輸入APIKEY</h4><pre>export NVIDIA_API_KEY=&quot;nvapi-…&quot;</pre><h3>二、安裝docker</h3><h4>2.1 按照官方說明安裝docker-ce</h4><p>Docker-ce 代表 Docker Community Edition，特點如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*N2Ah2wDKrbtKFjok3o4yBw.png" /></figure><p>可直接依序複製以下程式碼安裝，官方文件在<a href="https://docs.docker.com/engine/install/ubuntu/">此網頁</a>中的 “Install using the apt repository” 部分。</p><h4>2.2 設置Docker的apt儲存庫</h4><pre># Add Docker&#39;s official GPG key:<br>sudo apt-get update<br>sudo apt-get install ca-certificates curl<br>sudo install -m 0755 -d /etc/apt/keyrings<br>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc<br>sudo chmod a+r /etc/apt/keyrings/docker.asc<br><br># Add the repository to Apt sources:<br>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br>  $(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \<br>  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br>sudo apt-get update</pre><h4>2.3 安裝Docker套件</h4><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><h4>2.4 透過運行hello-world圖像來驗證Docker引擎安裝是否成功</h4><pre>sudo docker run hello-world</pre><h4>2.5 讓 Docker 可以在沒有 sudo 的情況下運行</h4><pre>sudo groupadd docker<br>sudo usermod -aG docker $USER<br>newgrp docker<br>docker run hello-world</pre><h3>三、安裝 nvidia-container-toolkit</h3><p>NVIDIA Container Toolkit 是一套工具，允許用戶在Docker容器中輕鬆部署和運行利用NVIDIA GPU的應用程序。它包括 NVIDIA Docker、GPU支持的容器運行時和其他關鍵組件，透過這些配置，容器能夠更有效地使用主機上的 NVIDIA GPU，從而提高運算效率和性能。<a href="https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html">[官方安裝網頁]</a></p><h4>3.1 配置環境軟體庫:</h4><p>導入 GPG 鑰匙，並從 NVIDIA 提供的 URL 下載軟體庫的列表文件，修改該文件並使用 GPG 鑰匙進行簽名驗證，最後將文件添加到系統的軟體源列表中。</p><pre>curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \<br>  &amp;&amp; curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \<br>    sed &#39;s#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g&#39; | \<br>    sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list</pre><p>Optionally, configure the repository to use experimental packages:</p><pre>sudo sed -i -e &#39;/experimental/ s/^#//g&#39; /etc/apt/sources.list.d/nvidia-container-toolkit.list</pre><h4>3.2 安裝 NVIDIA Container Toolkit</h4><pre>sudo apt-get update<br>sudo apt-get install -y nvidia-container-toolkit</pre><h4>3.3 配置Docker</h4><p>更新 /etc/docker/daemon.json 文件並重啟 Docker，確保 Docker 可以使用 NVIDIA Container Runtime</p><pre>sudo nvidia-ctk runtime configure --runtime=docker<br>sudo systemctl restart docker</pre><p>更新 /etc/containerd/config.toml 文件並重啟 containerd，確保 containerd 能夠使用 NVIDIA Container Runtime.</p><pre>sudo nvidia-ctk runtime configure --runtime=containerd<br>sudo systemctl restart containerd</pre><h3>四、執行範例</h3><pre>cd GenerativeAIExamples</pre><pre>docker compose --env-file deploy/compose/compose.env -f deploy/compose/rag-app-structured-data-chatbot.yaml build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLXaGe149QG-d5CcxF3Dmw.png" /></figure><p>大約經過15分鐘後完成，執行以下指令啟動Docker</p><pre>docker compose --env-file deploy/compose/compose.env -f deploy/compose/rag-app-structured-data-chatbot.yaml up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7tHpOBHIc6GYFn2_OF7Qw.png" /></figure><p>執行以下指令檢查Docker運作狀態</p><pre><br>docker ps --format &quot;table {{.ID}}\t{{.Names}}\t{{.Status}}&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hbSYDEu9mhfBGJwzhcM5g.png" /></figure><p>可透過執行以下指令停止容器：</p><pre>docker compose -f deploy/compose/rag-app-structured-data-chatbot.yaml down</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mld0UBjMuGt-WqxA1ympxw.png" /></figure><h3>五、進入聊天機器人介面</h3><h4>5.1 打開Chatbot聊天介面</h4><p>在瀏覽器輸入以下網址:</p><pre>http://localhost:8090/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mqc7r0kJDOEM2gS-zT-xHQ.png" /></figure><p>嘗試在聊天區輸入Hi送出，看是否能與模型對話。如果運作發生問題，回到Ubuntu輸入以下指令查詢</p><pre>docker ps<br>docker logs chain-server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bs82F7d3h-RAbnmZx1y5-g.png" /></figure><h4>5.2 執行預設的CSV文檔問答範例</h4><p>點選Knowledge Base ，上傳一份CSV到知識庫，預設為PdM_machines這份檔案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*jm-bzCalEvjDFusUnxCgaA.png" /></figure><h3>六、使用自己的CSV檔</h3><p>到下方路徑找到rag-app-structured-data-chatbot.yaml檔案，將預設的檔名PdM_machines改成自己的CSV檔名(第20行)，並儲存檔案。</p><pre>GenerativeAIExamples\deploy\compose\rag-app-structured-data-chatbot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*1rm7DouTYoVkVLIkbojROQ.png" /></figure><p>重新在Ubuntu執行以下指令:</p><pre>docker compose -f deploy/compose/rag-app-structured-data-chatbot.yaml down<br>docker compose --env-file deploy/compose/compose.env -f deploy/compose/rag-app-structured-data-chatbot.yaml build<br>docker compose --env-file deploy/compose/compose.env -f deploy/compose/rag-app-structured-data-chatbot.yaml up -d</pre><p><strong>6.1 英文資料問答實測</strong></p><p>以下是提供的資料格式:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*scIOE8bjXzNdmKHLjnPzug.png" /></figure><p>回到Converse頁面，勾選 Use knowledge base 選項，並開始對Llama3-70B模型進行問答。詢問問題: 四間餐廳在2016年情人節的總顧客數是多少?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LN4gcfBqLtVU1LZrqPIDcw.png" /></figure><p>中文詢問表現測試，詢問餐廳一在2016年的總來客數以及每日來客平均數</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myTPMwnd3juKbs-Ep0h2cQ.png" /></figure><p>有時候中文詢問會失敗，可以換成英文，並用較明確的問法</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBBkMx-5FjKRytKwNyad0Q.png" /></figure><p>詢問四間餐廳哪兩間的相關係數最高，剛開始不能回答，但加上list的概念詢問就可順利解決。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwN2VEBzXYWghiUi-aeJww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVnthRDOhIXoZ7LkDhIUHQ.png" /></figure><h3><strong>七、加上 NVIDIA Riva</strong></h3><p>您也可以選擇部署 NVIDIA Riva。 Riva 可以使用自動語音辨識來轉錄問題，並使用文字轉語音大聲說出答案，後續將補上詳細操作說明。</p><p>我是Ethan，目前為台灣人工智慧學校AI工程師、大型語言模型實作班講師，工作之餘也持續在開發者社群分享NVIDIA SDK的技術應用。歡迎透過Email與我聯繫: ison0615@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c607cc43e851" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用Google Colab + ngrock + Streamlit 運行LLM]]></title>
            <link>https://medium.com/@ethankuo_74456/%E4%BD%BF%E7%94%A8google-colab-ngrock-streamlit-%E9%81%8B%E8%A1%8Cllm-59f393e689c8?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/59f393e689c8</guid>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Sat, 04 May 2024 02:14:09 GMT</pubDate>
            <atom:updated>2024-10-14T05:58:13.060Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>一、到</strong><a href="https://dashboard.ngrok.com/get-started/setup/windows"><strong>ngrock網站</strong></a><strong>申請Authyoken</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*HnY5IGD5RMgEyguoaSWa3A.png" /></figure><p><strong>二、執行以下 Google Colab</strong></p><p>先複製一份到自己的雲端硬碟，更換NGROCK的Token後再執行程式</p><p><a href="https://colab.research.google.com/drive/1lvUbm2_L3pkL9EznETeY7hjFzKbEe7O6?authuser=1#scrollTo=e9e9QOWD-l7k">Mistral_7b_FastAPI_Service_Colab_Example_External_Version.ipynb</a></p><p><strong>三、將以下Streamlit 程式碼存成main.py</strong></p><pre>import streamlit as st<br>import requests<br>import json<br><br>st.title(&quot;ChatBot&quot;)<br><br>url = st.sidebar.text_input(&#39;API URL&#39;, &#39;Put the URL here.&#39;)<br>system_prompt = st.sidebar.text_input(&#39;System prompt&#39;, &quot;你是一個有幫助的問答機器人，請用繁體中文回覆。&quot;)<br><br>def response_api(prompt, url, system_prompt):<br>    payload = json.dumps({<br>      &quot;messages&quot;: [<br>        {<br>          &quot;role&quot;: &quot;system&quot;,<br>          &quot;content&quot;: system_prompt<br>        },<br>        {<br>          &quot;role&quot;: &quot;user&quot;,<br>          &quot;content&quot;: prompt<br>        }<br>      ]<br>    })<br>    headers = {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    }<br><br>    response = requests.request(&quot;POST&quot;, url, headers=headers, data=payload)<br><br>    return response.json()[&quot;choices&quot;][0][&quot;message&quot;][&#39;content&#39;]<br><br><br># Initialize chat history<br>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = []<br><br># Display chat messages from history on app rerun<br>for message in st.session_state.messages:<br>    with st.chat_message(message[&quot;role&quot;]):<br>        st.markdown(message[&quot;content&quot;])<br><br># React to user input<br>if prompt := st.chat_input(&quot;請在此詢問問題。&quot;):<br>    # Display user message in chat message container<br>    st.chat_message(&quot;user&quot;).markdown(prompt)<br>    # Add user message to chat history<br>    st.session_state.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br><br>    # Display assistant response in chat message container<br>    response = response_api(prompt, url, system_prompt)<br>    with st.chat_message(&quot;assistant&quot;):<br>        st.markdown(response)<br>    # Add assistant response to chat history<br>    st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: response})</pre><p><strong>四、進入IDE介面並運行指令:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*CxeP8xJ9WIpSKToeERir4w.png" /></figure><pre>streamlit run main.py</pre><p>會彈出Streamlit聊天頁面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgRen0TezuoZEKO1rg6T1g.png" /></figure><p><strong>五、點選Colab的URL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*MS5tEI7rqNM6YZLlC3ys9g.png" /></figure><p>複製以下頁面網址</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*-PW5AHC_n9uwvPjvx8VKCQ.png" /></figure><p>貼到聊天介面 API URL 的欄位</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Wxr3zcqT9d85N0NtPb9PIg.png" /></figure><p>完成，即可開始與大型語言模型互動 !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59f393e689c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[NVIDIA 開發百寶箱] — Chat with RTX安裝及使用]]></title>
            <link>https://medium.com/@ethankuo_74456/nvidia-%E9%96%8B%E7%99%BC%E7%99%BE%E5%AF%B6%E7%AE%B1-chat-with-rtx%E5%AE%89%E8%A3%9D%E5%8F%8A%E4%BD%BF%E7%94%A8-df8509faf816?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/df8509faf816</guid>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 08:52:28 GMT</pubDate>
            <atom:updated>2024-05-08T03:41:54.445Z</atom:updated>
            <content:encoded><![CDATA[<h3>[NVIDIA 開發百寶箱] — 安裝 Chat RTX 為 NVIDIA RTX AI PC 量身打造聊天機器人</h3><h4>前言</h4><p>2024年2月，NVIDIA 釋出 <a href="https://chat-withrtx.com/">Chat RTX</a> 的簡易安裝包。讓一般民眾可以透過有 RTX 顯卡的電腦運行大型語言模型，實現客製化的 AI 知識助理，最重要的是整個系統都是安裝於本機端，具有資安優勢。</p><p>ChatRTX 展現出利用 RTX GPU 加速 LLM 的潛力，這款應用是使用 GitHub 上的 TRT-LLM RAG on Windows 專案。開發者可以依自身硬體資源參考該專案，或參考此篇部落格文章-<a href="https://developer.nvidia.com/blog/get-started-with-generative-ai-development-for-windows-pcs-with-rtx-systems">開始為搭載 NVIDIA RTX 的 Windows PC 開發生成式 AI</a>。</p><h4>一、Github 專案特點</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*vRmuYzeOl_maXqNjd7AwRg.png" /></figure><p><a href="https://github.com/NVIDIA/trt-llm-rag-windows">TRT-LLM RAG on Windows</a> 專案有以下幾個特點:</p><p><strong>1.1 使用 LlamaIndex 框架</strong><br> <br>Llama Index 是一個用於管理、儲存大量文檔向量表示的框架，透過 Llama Index，可以對許多資料類型(如文檔、PDF、SQL資料庫等)建立索引並進行高效率的檢索。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRv9a5aIWDSOmS4DzldQBw.png" /><figcaption><a href="https://github.com/sugarforever/LlamaIndex-Tutorials/tree/main/01_Introduction">LlamaIndex-Tutorials/01_Introduction at main · sugarforever/LlamaIndex-Tutorials (github.com)</a></figcaption></figure><p><strong>1.2使用 開源 FAISS 向量資料庫</strong></p><p>LlamaIndex 下的開源向量資料庫 <a href="https://github.com/facebookresearch/faiss">FAISS </a>(Facebook AI Similarity Search)，是一個功能強大且高效的相似度搜索和相似度索引函式庫，由 Meta 的人工智慧研究小組所開發。包含了數種向量相似度搜尋演算法，可搜尋任意長度的向量集，特別適合處理高維數據。關於程式應用可在<a href="https://docs.llamaindex.ai/en/stable/examples/vector_stores/FaissIndexDemo/">Faiss Vector Store</a> 找到。</p><p>在具有 GPU 的電腦或伺服器上，可以使用 GPU 替代 CPU 加速向量索引，輸入和輸出都在 GPU 上進行能讓大型語言模型更快的回應。也支援多 GPU 使用。</p><p><strong>1.3 使用 Tensor-RT LLM 加速</strong></p><p><a href="https://github.com/NVIDIA/TensorRT-LLM/">TensorRT-LLM</a> 是一個用於加速 LLM 推論的開源專案， 允許使用不同的量化模式(INT4 或 INT8 權重) 執行 LLM 模型。在<a href="https://blogs.nvidia.com/blog/tensorrt-llm-windows-stable-diffusion-rtx/">這篇文章</a>中指出透過 TensorRT-LLM for Windows，PC 上的生成式 AI 速度提升了 4 倍。關於支援TensorRT 優化的開源模型，可在<a href="https://nvidia.github.io/TensorRT-LLM/reference/support-matrix.html">此連結</a>找到。</p><h4>二、ChatRTX 電腦硬體需求規格</h4><p>要執行 ChatRTX 的話，電腦需要配備 GeForce RTX 30、40 系列以上 GPU，或 RTX Ampere、Ada Generation GPU。除此之外，顯示卡記憶體最少需 8GB 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*9UaTXa_zCT5jjYrv9Nkf5A.png" /></figure><p>驅動程式需為535.11版本以上，如果版本過舊在安裝時會出現以下錯誤:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Jmt-8oZlsG0gSiQok67l5A.png" /></figure><p>可使用<a href="https://medium.com/@ethankuo_74456/nvidia-%E9%96%8B%E7%99%BC%E7%99%BE%E5%AF%B6%E7%AE%B1-%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%B6%E4%BD%A0%E5%9C%A8-wsl2-%E7%92%B0%E5%A2%83%E5%AE%89%E8%A3%9D-nvidia-tao-toolkit-ef647bc32c98">本系列之前文章</a>提到的 <a href="https://www.nvidia.com/zh-tw/geforce/geforce-experience/">Genforce Experience</a> 來更新驅動程式版本</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*m3oJFQuTcRkM1TH-I65YMg.png" /></figure><p><strong>三、安裝ChatRTX注意事項</strong><br><br>安裝前建議先<strong>關閉電腦的防毒軟體</strong>，否則可能在啟動時無法順利執行。接著從Nvidia提供的下載連結下載檔案，檔案共有35G，下載需要一段時間。</p><p><strong>3.1. 安裝流程</strong></p><p>下載後解壓縮進入 ChatWithRTX_installer_3_5 資料夾，執行安裝程式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*4hhR6Yj88qJwmJ4mulP-vA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*s8EZGfEfIifIEgxe3AvYQg.png" /></figure><p>通過環境檢測後即進入安裝流程，由於安裝後TensorRT-LLM還會進行模型的優化，第一次安裝約需要一小時左右，可以先去喝杯咖啡。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*DclJ1o38I-NkR42wRVgPXQ.png" /></figure><p>預設安裝在以下路徑，建議不要自行更改安裝路徑以免造成不必要的麻煩</p><p>C:\Users\使用者名稱\AppData\Local\NVIDIA</p><p>安裝完成後即可在桌面上看到執行程式Icon，點選後等待一段時間即可進入聊天頁面，如果發生錯誤可參考後面的debug說明。</p><p><strong>3.2 開啟 ChatRTX 時可能遇到的問題解法</strong></p><p>雖然是簡易安裝包，實際點Icon執行時仍可能遇到一些問題，在<a href="https://forums.developer.nvidia.com/t/chat-with-rtx-error-modulenotfounderror-no-module-named-sentence-transformers/283151">論壇</a>中有許多使用者在開啟時程式找不到 sentence_transformers 這個 package，以下提供筆者的解決方式，同時也繼續紀錄其他問題的解法</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WN3ecelevea9DGhs-FOhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyKme-sWYQCsYedCpHdAhA.png" /></figure><p>a.進入以下資料夾路徑並找到 app_launch.bat 檔案</p><p>C:\Users\ison0\AppData\Local\NVIDIA\ChatWithRTX\RAG\trt-llm-rag-windows-main</p><p>b.使用Visual Studio 開啟 (或在檔案上按右鍵選擇用記事本編輯)，並將以下兩行加入程式中</p><p>! pip install -U sentence-transformers<br>! pip install -U transformers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*8DHehXj_7UZeDMjXrcDBZQ.png" /></figure><p>c. 重新點選桌面的執行 Icon 啟用命令提示字元，在 Miniconda 環境中更新 sentence-transformer 和 transformer 的 package，等待一點時間後順利進入Chat with RTX聊天頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czq7-Xb2Udf8aFQOs-VK6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nlqqt1oqJJEqTGgUO84UpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cd0Yj8c2tGcYpclYcbw3fw.png" /></figure><h4>四、ChatRTX 可用的開源模型</h4><h4>4.1 Mistral 7B 與 Llama 2 13B</h4><p>NVIDIA 目前提供 Mistral 7B INT4 和 Llama2 13B INT4 兩個模型下載，但如果顯卡的 VRAM 只有 8GB，只能裝得下Mistral 7B 模型進行推論 ，因此在安裝時不會看到 Llama2 13B 的選項。不過Mistral 7B 在MMLU(多領域知識)、推理能力、閱讀理解和中文能力都贏過比他肥大的Llama2 13B，只有在世界知識測試表現相當，VRAM不足的朋友影響不大。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*guHR0M7uPD7vNd1iDeZIDw.png" /></figure><p>註 : MMLU（massive multitask language understanding，大規模多任務語言理解）的評測結合了 57 個領域，用來測試 AI 模型的知識和解決問題的能力，包括數學、物理、歷史、法律、醫學、倫理等等</p><p><strong>4.2 模型參數與量化說明</strong><br> <br>7B 模型 有 70 億個參數左右，INT4 指的是使用 4 位整數進行量化，這是一種將模型部署到具有限制性資源硬體上的優化技術（例如移動設備和嵌入式系統），有以下優勢:</p><ol><li><strong>降低GPU記憶體需求：</strong></li></ol><p>通常模型使用的是 32 位浮點數（FP32）來儲存權重和執行運算。將這些數據量化到 4 位整數（INT4）可以顯著減少模型的記憶體占用。這代表著模型的大小可以減少到原來的 1/8，使其更適合部署在記憶體受限的設備上。以下是 Mistral 7B 約73億個參數量計算所得結果:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*jSeYIAfelWUAufDrqkQwnA.png" /></figure><p><strong>2.加速推論：</strong></p><p>使用較低位數的 INT4 可以提高計算效率，因為整數運算通常比浮點數運算更快，使得模型在推論時能夠達到更快的執行速度。</p><h4>五、問答實測</h4><h4>5.1 一般 Chat 實測</h4><p>程式測試:</p><p>→ 回覆程式碼狀況不錯，可以得到完整結果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctypYg0Cr2f2VRSBtcUAVA.png" /></figure><p><strong>5.2 檢索增強生成 （Retrieval-Augmented Generation, RAG）</strong><br>檢索增強生成技術(RAG)是當下LLM開發者的熱門話題，其原理是將特定知識文檔切割成許多塊 (Chunks 或 Spilts)，再透過嵌入模型 (Embedding model) 轉為向量後儲存於向量資料庫</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*6dfW8a5jjXWi3igffDSYBw.png" /><figcaption>Image Reference: <a href="https://blog.csdn.net/weixin_42608414/article/details/132039304">https://blog.csdn.net/weixin_42608414/article/details/132039304</a></figcaption></figure><p>當用戶問問題時，大型語言模型(LLM)會檢索與問題相近的內容，並與用戶的Prompt結合產生新的prompt，可讓LLM產生更精準的回應，不用耗費大量金錢成本微調模型，就可以產生特定情境下的AI助理。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*3vIJFmESdfroj3uOgSB9jw.png" /><figcaption>Image Reference: <a href="https://blog.csdn.net/weixin_42608414/article/details/132039304">https://blog.csdn.net/weixin_42608414/article/details/132039304</a></figcaption></figure><p>對資料有隱私性的個人或企業用戶而言，使用雲端RAG應用服務有洩漏機敏性資料的風險，導致在本機端(地端)運行大語言模型需求日漸提升，然而在全地端執行RAG通常需要較高的技術門檻，對初階開發者而言不易上手，目前有一些標榜地端RAG的應用仍然會透過API外接雲端向量資料庫，這依然存在資訊外流的風險。</p><p><strong>5.3 將你的知識庫文檔進行 Embedding</strong><br>建立mydataset知識庫資料夾放入知識文檔。筆者放入 Attention is all you need 的論文、以及高中數學第三冊、第四冊的教科書內容、生成式AI的講義等。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*pEeB26lqaDUHIBykhf_mow.png" /></figure><p>回到聊天頁面選取資料夾路徑，並點選右上角的更新</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*7D1K7HdF2pNLTwvKUYGMRw.png" /></figure><p>在命令提示介面可以看到文檔正在進行Embedding 轉換並儲存於向量資料庫，速度會依顯卡等級而定</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*2CJORfRdZxbdpN5d4J10gQ.png" /></figure><p>Embedding 後在與mydataset資料夾同一層的路徑中可找到一個系統新建立的 mydataset_vector_embedding 資料夾，檔案以Jason檔格式儲存。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*zqvcqVboc2vJg6dhriwcxQ.png" /></figure><p><strong>5.4 幾個 RAG 實測結果</strong></p><p>矩陣的乘法如何計算? 請以繁體中文回答</p><p>→ 檢索到文檔並正確回應</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Xdor-DGMLRLjfTuSQy5Mg.png" /></figure><p>Attention 的機制是什麼?</p><p>→ 檢索到文檔並正確回應，但使用英文回覆，可能因為原文檔是英文 paper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xK78nAGrYqyFL_R_WbHEQ.png" /></figure><p>What is Attention? please answer in traditional chinese!</p><p>→ 檢索到文檔並以中文正確回應，但出現奇怪的符號</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6yFq7kCotDW_kkrvEWzSA.png" /></figure><p>何謂條件機率?</p><p>→ 為避免出現符號，用英文來發問能正確檢索中文教科書文檔，並得到恰當的回應</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4T8ogR_Lm9Ky-iFu66pNg.png" /></figure><h4><strong>六、結語</strong></h4><p>開源大型語言模型在 PC 與邊緣端的運行需求促成了 AIPC 的軍備競賽，目前的 mistral 7B 模型能滿足特定問答與 RAG 需求，但在中文聊天尚有很大的改善空間。期待NVIDIA未來能將更多 TensorRT-LLM 支援的開源模型整合進此服務中，讓初入門的玩家有更多選擇。此專案的價值在於提供了全地端RAG的部署框架，開發者可運用下載的Docker工具包做進一步的專案開發，未來有新增模型將繼續與大家分享。</p><h4><strong>七、相關參考資源</strong></h4><p><a href="https://slashdot.org/software/vector-databases/?sort=rating_count">Top Vector Databases in 2024 (slashdot.org)</a><br><a href="https://engineering.fb.com/2017/03/29/data-infrastructure/faiss-a-library-for-efficient-similarity-search/">Faiss：高效相似性搜索庫 — Meta 工程部 (fb.com)</a><br><a href="https://aws.plainenglish.io/unlocking-faiss-for-efficient-search-vector-indexing-and-ann-with-serverless-architecture-5b2b59ead20f">解鎖 FAISS：使用無伺服器架構實現向量索引和 ANN </a><br><a href="https://myscale.com/blog/beginners-guide-faiss-llamaindex-integration-efficient-vector-storage/">掌握 Faiss 和 LlamaIndex 集成，實現高效的載體存儲 (myscale.com)</a><br><a href="https://learnbybuilding.ai/tutorials/rag-chatbot-on-podcast-llamaindex-faiss-openai">使用 LlamaIndex、FAISS 和 OpenAI 構建 RAG 聊天機器人 </a><br><a href="https://cloud.baidu.com/article/3256517">LlamaIndex深度解析：配置篇 (baidu.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df8509faf816" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[NVIDIA 開發百寶箱] — 手把手帶你在 WSL2 環境安裝 NVIDIA TAO Toolkit]]></title>
            <link>https://medium.com/@ethankuo_74456/nvidia-%E9%96%8B%E7%99%BC%E7%99%BE%E5%AF%B6%E7%AE%B1-%E6%89%8B%E6%8A%8A%E6%89%8B%E5%B8%B6%E4%BD%A0%E5%9C%A8-wsl2-%E7%92%B0%E5%A2%83%E5%AE%89%E8%A3%9D-nvidia-tao-toolkit-ef647bc32c98?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef647bc32c98</guid>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 17:34:02 GMT</pubDate>
            <atom:updated>2024-11-16T03:28:42.482Z</atom:updated>
            <content:encoded><![CDATA[<h3>[NVIDIA 開發百寶箱] — 手把手帶你在 WSL2 環境安裝 NVIDIA TAO Toolkit</h3><p>您是否曾夢想在自己裝有NVIDIA顯卡的電腦上使用NVIDIA TAO Toolkit 進行前沿的遷移學習，卻在實踐過程中遭遇重重挑戰？想要親手訓練AI模型，卻又擔心珍貴的訓練數據在上傳到雲端的過程中泄露？在這篇文章中我們將帶您一步步在自己的電腦中安裝NVIDIA TAO Toolkit，讓您在家中也能享受專業級的AI開發體驗。</p><p>TAO 全名為 Train, Adapt and Optimise（訓練、適應、最佳化），這是一種基於 GUI 的框架，目的是讓企業 AI 應用和服務的開發更加輕便、容易、迅速。TAO 結合了遷移學習（transfer learning）和其他機器學習算法，透過 NVIDIA 提供的多種預訓練模型，你只需要加入小量數據進行微調，即可高效部署 AI。</p><p>本指南將示範如何使用 Windows Linux 子系統安裝 Ubuntu-20.04，並且安裝 NVIDIA TAO 框架以及所需要的環境。</p><h3>一、安裝前準備</h3><p>查看本機環境是否符合TAO的最低需求，也可到 <a href="https://docs.nvidia.com/tao/tao-toolkit/text/tao_toolkit_quick_start_guide.html">TAO Toolkit Quick Start Guide</a> 網頁查詢。</p><h4>1.1 Hardware Requirements</h4><pre>| Configuration | System RAM | GPU RAM | CPU    | GPU          | SSD Space |<br>|---------------|------------|---------|--------|--------------|-----------|<br>| Minimum       | 8 GB       | 4 GB    | 8 core | 1 NVIDIA GPU | 100 GB    |<br>| Recommended   | 32 GB      | 32 GB   | 8 core | 1 NVIDIA GPU | 100 GB    |</pre><h4>1.2 Software Requirements</h4><pre>| Software                   | Version       | Comment                                 |<br>|----------------------------|---------------|-----------------------------------------|<br>| Ubuntu LTS                 | 20.04         |                                         |<br>| python                     | &gt;3.7,&lt;=3.10   | Not needed if you use TAO toolkit API   |<br>| docker-ce                  | &gt;19.03.5      | Not needed if you use TAO toolkit API   |<br>| docker-API                 | 1.40          | Not needed if you use TAO toolkit API   |<br>| nvidia-container-toolkit   | &gt;1.3.0-1      | Not needed if you use TAO toolkit API   |<br>| nvidia-container-runtime   | 3.4.0-1       | Not needed if you use TAO toolkit API   |<br>| nvidia-docker2             | 2.5.0-1       | Not needed if you use TAO toolkit API   |<br>| nvidia-driver              | &gt;535.xx       | Not needed if you use TAO toolkit API   |<br>| python-pip                 | &gt;21.06        | Not needed if you use TAO toolkit API   |</pre><p>官網中提到運行TAO有四種方式，本篇將帶大家以第一種 <strong>Launcher CLI</strong>的方式安裝。作業系統建議以<strong>Windows 10、版本2004以上</strong>的更新版本執行，(組建 19041 和更新版本)，或是 <strong>Windows 11</strong>。</p><h4>1.3 使用 Genforce Experience 更新顯卡驅動程式與Cuda版本</h4><p>更新後的TAO對Nvidia Driver的最低需求是525.85之後的版本，如果版本太舊將會導致模型無法訓練，建議使用NVIDIA的 <a href="https://www.nvidia.com/zh-tw/geforce/geforce-experience/">GeForce Experience</a> 軟體，可以查看目前自己電腦安裝的版本，並一鍵更新到最新版的驅動程式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h_nmVTcb75d0by8c.png" /></figure><p>也可用此<a href="https://www.nvidia.com/Download/index.aspx">網站</a>查詢自己顯卡能安裝的版本後再用 GeForce Experience 下載</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*dxPPnp0GXmv9b7D3.png" /></figure><h4>1.4 Windows terminal安裝 (optional)</h4><p>您可以使用內建的 powershell，如果追求一些有趣的視覺效果，可以到 windows store 安裝 windows terminal 來客製化終端機的介面。</p><p>安裝完畢後可先關掉Powershell視窗，並到微軟的Microsoft store中搜尋”<strong>windows terminal</strong>”並安裝</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*V_2NTSGtJa4xfQ9s.png" /></figure><h3>二、安裝 WSL2 Ubuntu-20.04</h3><p>WSL2（Windows Subsystem for Linux Version 2）是開發人員在 Windows 環境中使用 Linux 的理想選擇，其提供了一個完整的 Linux 內核直接在 Windows 中運行，從而實現了優化的文件系統性能和更高的系統調用兼容性。它允許無需雙重啟動或設置傳統虛擬機就能高效地運行 Linux 環境，並支持 Linux 圖形應用程序及 GPU 加速。</p><h4>2.1 安裝 windows terminal</h4><p>首先以<strong>系統管理員</strong>身分開啟 windows powershell<br>使用 WSL 安裝 Linux 的發行版本，先將預設的 WSL 版本改成 2 代替舊版的 1。</p><pre>wsl --set-default-version 2</pre><p>接著安裝 Linux 發行版本 Ubuntu-20.04 ，目前 NVIDIA 的 AI 框架大部分都支援這個版本</p><pre>wsl --install -d Ubuntu-20.04</pre><p>設定作業系統的使用者帳號以及密碼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nn_L3xrYT2GHmkRw.png" /></figure><p>完成後等待一段時間，直到綠色使用者名稱出現後關閉powershell並開啟windows terminal</p><p>進入 windows terminal 以後，在 powershell 的 tab 輸入下列指令，可以更新 Linux 的核心。</p><pre>wsl --update</pre><p>更新完 kernel 之後，接下來可以進入windows terminal 簡單的調整一下 Ubuntu-20.04 的終端機效果，本篇範例在外觀設定選項當中將顯示的字體加大、並且啟用了舊化的介面風格。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_HXQIV5VuO5dmlcr.png" /></figure><h4>2.2 進入Ubuntu-20.04</h4><p>打開 windows terminal 並且選擇添加一個 Ubuntu-20.04 的 tab 就可以啟用。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I-3yTn-e6jOSbudL.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ah7bFacJCyRPwxnG.png" /></figure><p>如果進入後沒有看到如上圖顯示綠色的用戶名稱而是看到白色的root，這代表您以 root 身份運行終端：需要切換使用者帳戶，請輸入以下指令</p><pre>su - 使用者名稱</pre><p>P.S.若之後重登入到這裡使用者名稱還沒有變綠色，通常是因為用戶的 shell 配置文件（如 .bashrc 或 .bash_profile）中的設定有所遺失或更改，執行以下將其恢復到預設設定即可</p><pre>source ~/.bashrc</pre><h4>2.3 開始安裝套件</h4><p>首先更新 Ubuntu 當中的套件，並將已經安裝的套件升級到最新版本。</p><pre>sudo apt-get update<br>sudo apt-get upgrade</pre><p>安裝 gedit文本編輯器。</p><pre>sudo apt install gedit -y</pre><p>接下來，我們將安裝一些在安裝過程中以及將來可能需要的基本套件，並刪除不需要的套件。</p><pre>sudo apt-get install -y build-essential cmake gfortran git pkg-config<br>sudo apt-get install -y python-dev software-properties-common wget vim<br>sudo apt-get autoremove</pre><h4>2.4 建立 Python 鏈結</h4><p>WSL2 安裝的 Ubuntu 應該都會遇到的一個問題就是，WSL 雖然已有內附的 python ，但是輸入 python 卻會找到比較舊的版本，需要使用指令將Python指向buntu-20.04 內建的Python 3.8版本。</p><p>使用以下指令先將舊版本移除，再輸入相應的指令以建立鏈結，完成後再使用 python 指令可以確認已經成功。</p><pre>sudo rm /usr/bin/python<br>sudo ln -s /usr/bin/python3.8 /usr/bin/python</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l0S7SP2CevMcCe8n.png" /></figure><h3>三、 安裝其他重要套件</h3><p>安裝Linux 系統（如 Ubuntu）上各種開發和科學計算相關的工具包</p><pre>sudo apt-get install -y --no-install-recommends libboost-all-dev doxygen<br>sudo apt-get install -y libgflags-dev libgoogle-glog-dev liblmdb-dev libblas-dev<br>sudo apt-get install -y libatlas-base-dev libopenblas-dev libgphoto2-dev libeigen3-dev libhdf5-dev<br>sudo apt-get install -y python3-dev python3-pip python3-nose python3-numpy python3-scipy</pre><h3>四、 安裝 docker</h3><p>Docker 是一個開源的應用容器引擎，允許開發者將應用程式打包進容器（containers），這些容器在不同的計算環境中都能夠一致地運行。NVIDIA 的 AI 框架幾乎都是封裝成容器，所以安裝 docker 是必要步驟，按照 docker 官方網頁的步驟即可快速完成。</p><h4>4.1 按照官方說明安裝docker-ce</h4><p>Docker-ce 代表 Docker Community Edition，特點如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*-l-7ED7JL663w8Gp7dQHcQ.png" /></figure><p>可直接依序複製以下程式碼安裝，官方文件在<a href="https://docs.docker.com/engine/install/ubuntu/">此網頁</a>中的 “Install using the apt repository” 部分。</p><h4>4.2 設置Docker的apt儲存庫</h4><pre># Add Docker&#39;s official GPG key:<br>sudo apt-get update<br>sudo apt-get install ca-certificates curl gnupg<br>sudo install -m 0755 -d /etc/apt/keyrings<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg<br>sudo chmod a+r /etc/apt/keyrings/docker.gpg</pre><pre># Add the repository to Apt sources:<br>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] <a href="https://download.docker.com/linux/ubuntu">https://download.docker.com/linux/ubuntu</a> \<br>  $(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \<br>  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br>sudo apt-get update</pre><h4>4.3 安裝Docker套件</h4><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><h4>4.4 透過運行hello-world圖像來驗證Docker引擎安裝是否成功</h4><pre>sudo docker run hello-world</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*REkqxfpGqKOB1eNI.png" /></figure><h4>4.5 讓 Docker 可以在沒有 sudo 的情況下運行</h4><pre>sudo groupadd docker<br>sudo usermod -aG docker $USER<br>newgrp docker<br>docker run hello-world</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jj27ZLToe8DofbVV.png" /></figure><h3>五、安裝 nvidia-container-toolkit</h3><p>NVIDIA Container Toolkit 是一套工具，允許用戶在Docker容器中輕鬆部署和運行利用NVIDIA GPU的應用程序。它包括 NVIDIA Docker、GPU支持的容器運行時和其他關鍵組件，透過這些配置，容器能夠更有效地使用主機上的 NVIDIA GPU，從而提高運算效率和性能。<a href="https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html">[官方安裝網頁]</a></p><p>5.1 配置環境軟體庫:</p><p>導入 GPG 鑰匙，並從 NVIDIA 提供的 URL 下載軟體庫的列表文件，修改該文件並使用 GPG 鑰匙進行簽名驗證，最後將文件添加到系統的軟體源列表中。</p><pre>curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \<br>  &amp;&amp; curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \<br>    sed &#39;s#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g&#39; | \<br>    sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list</pre><p>Optionally, configure the repository to use experimental packages:</p><pre>sudo sed -i -e &#39;/experimental/ s/^#//g&#39; /etc/apt/sources.list.d/nvidia-container-toolkit.list</pre><h4>5.2 安裝 NVIDIA Container Toolkit</h4><pre>sudo apt-get update<br>sudo apt-get install -y nvidia-container-toolkit</pre><h4>5.3 配置Docker</h4><p>更新 /etc/docker/daemon.json 文件並重啟 Docker，確保 Docker 可以使用 NVIDIA Container Runtime</p><pre>sudo nvidia-ctk runtime configure --runtime=docker<br>sudo systemctl restart docker</pre><p>更新 /etc/containerd/config.toml 文件並重啟 containerd，確保 containerd 能夠使用 NVIDIA Container Runtime.</p><pre>sudo nvidia-ctk runtime configure --runtime=containerd<br>sudo systemctl restart containerd</pre><h3>六、NGC Catalog</h3><h4>6.1 註冊NGC帳戶並申請API key</h4><p>NVIDIA GPU Cloud (簡稱NGC)，是一個GPU加速軟體的資源管理平台，NGC的 資源包含經過優化的AI訓練框架、AI工具包、預訓練模型，以及各式各樣的範例程式碼，並且是可免費取得的。首先進入<a href="https://catalog.ngc.nvidia.com/?filters=&amp;orderBy=weightPopularDESC&amp;query=">NGC Catalog</a>網站，依照以下步驟產生API KEY:</p><ul><li>在網站右上角，點選用戶帳號，然後選擇“設置”（Setup）</li><li>在設置頁面上，點選“獲取 API key”（Get API Key）來打開“設置 &gt; API Key”頁面。</li><li>點擊“獲取 API Key”按鈕以生成您的 API 鑰匙，產生後將<strong>API Key</strong>、<strong>Username</strong>、<strong>Psaaward</strong>複製到自己的記事本存放。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rxgbS8PI7Aewca2V.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kTy1Mcw3C4rTT2U0.png" /></figure><h4>6.2 NVCR login</h4><p>接下來登錄到 NGC 的容器註冊中心 (NVIDIA Container Registry, <strong>NVCR</strong>)。</p><p>回到 Ubuntu20.04，執行以下命令時，它會提示你輸入用於登錄 NVCR 的用戶名和密碼(API Key)。這是存取和下載 NVIDIA提供的容器映像的必要步驟。</p><pre>sudo docker login nvcr.io</pre><pre>Username: &quot;$oauthtoken&quot;<br>Password: &quot;YOUR_NGC_API_KEY&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tzd3_xOD-yrRQvD1.png" /></figure><h3>七、安裝miniconda3虛擬環境</h3><p>使用以下四行命令快速安裝最新的miniconda 64位元版本。如要安裝Linux的Miniconda的不同版本或架構，請在wget命令中更改.sh安裝程序的名稱，官方說明<a href="https://docs.conda.io/projects/miniconda/en/latest/">點此</a>。</p><pre>mkdir -p ~/miniconda3<br>wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh<br>bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3<br>rm -rf ~/miniconda3/miniconda.sh</pre><p>安裝完成後，初始化您新安裝的Miniconda。以下命令為bash和zsh shells進行初始化，完成後須重啟terminal讓設定生效。</p><pre>~/miniconda3/bin/conda init bash<br>~/miniconda3/bin/conda init zsh</pre><p>在您安裝了miniconda之後，通過設置Python版本為3.7來創建一個新的虛擬環境。</p><pre>conda create -n launcher python=3.7</pre><p>啟動剛剛建立名稱為launcher的虛擬環境</p><pre>conda activate launcher</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*XZb-a15YI6wbTuJF.png" /></figure><h3>八、安裝 TAO Toolkit Launcher</h3><p>首先下載包含啟動腳本、Jupyter Notebook 和設定檔的 TAO 套件。</p><pre>wget --content-disposition https://api.ngc.nvidia.com/v2/resources/nvidia/tao/tao-getting-started/versions/5.1.0/zip -O getting_started_v5.1.0.zip<br>unzip -u getting_started_v5.1.0.zip  -d ./getting_started_v5.1.0 &amp;&amp; rm -rf getting_started_v5.1.0.zip &amp;&amp; cd ./getting_started_v5.1.0</pre><p>由於剛剛有重啟， 需要再登錄一次NGC container，執行一次以下指令後輸入剛才的帳號及密碼</p><pre>docker login -u &quot;$oauthtoken&quot; nvcr.io</pre><p>安裝 CLI 啟動器 (CLI launcher)</p><pre>bash setup/quickstart_launcher.sh --install</pre><p>日後可透過執行以下命令將啟動器更新到最新版本的 TAO Toolkit(初次安裝此步驟可略過)</p><pre>bash setup/quickstart_launcher.sh --upgrade</pre><p>如果遇到 tao binary wasn’t found 的錯誤，執行以下指令</p><pre>export PATH=$PATH:~/.local/bin</pre><h3>九、選用、運行 Docker</h3><h4>9.1 依照需求選擇docker容器</h4><p>NVIDIA TAO Toolkit 對<em>模型訓練</em>、<em>資料集處理</em>、<em>模型部署</em>等類別配置有多個docker容器，每個容器針對不同的任務或模型提供專屬環境和工具，這樣的設計使得用戶可以根據自己的具體需求選擇最合適的容器環境，輸入以下指令檢視不同容器支援的內容，從而提升開發效率和模型性能。</p><pre>tao info --verbose</pre><p><strong>TAO Toolkit Docker 容器配置</strong><br>(Version: 5.2.0.1 、 Published_date: 01/16/2024)</p><p><strong>模型訓練 (model)：</strong></p><p>例如 Docker 版本 5.0.0-tf1.15.5 支援 TensorFlow 1.15.5 的版本、5.2.0.1-pyt1.14.0 支援 PyTorch 1.14.0 的版本，餘以此類推，相關參考資源<a href="https://catalog.ngc.nvidia.com/orgs/nvidia/teams/tao/resources/tao-getting-started">點此</a>。</p><pre>| 類別   | Docker 版本         | 支援的任務 |<br>|--------|---------------------|------------|<br>| Model  | 5.0.0-tf2.11.0      | classification_tf2, efficientdet_tf2 |<br>| Model  | 5.0.0-tf1.15.5      | bpnet, classification_tf1, converter, detectnet_v2, dssd, efficientdet_tf1, faster_rcnn, fpenet, lprnet, mask_rcnn, multitask_classification, retinanet, ssd, unet, yolo_v3, yolo_v4, yolo_v4_tiny |<br>| Model  | 5.2.0-pyt2.1.0      | action_recognition, centerpose, deformable_detr, dino, mal, ml_recog, ocdnet, ocrnet, optical_inspection, pointpillars, pose_classification, re_identification, visual_changenet |<br>| Model  | 5.2.0.1-pyt1.14.0   | classification_pyt, segformer |</pre><p><strong>資料集處理 (dataset)：</strong><br>nvidia/tao/tao-toolkit 下還有專門用於數據集處理的 Docker 容器版本，如 <strong>5.2.0-data-services</strong>。這個容器提供了資料增強、自動標註和數據分析等任務的工具。</p><pre>**資料集處理 (dataset)：**<br>nvidia/tao/tao-toolkit 下還有專門用於數據集處理的 Docker 容器版本，如 **5.2.0-data-services**。這個容器提供了資料增強、自動標註和數據分析等任務的工具。<br>| 類別   | Docker 版本         | 支援的任務 |<br>|--------|---------------------|------------|<br>| Dataset| 5.2.0-data-services | augmentation, auto_label, annotations, analytics |</pre><p><strong>模型部署 (deploy)：</strong><br>nvidia/tao/tao-toolkit 中的 <strong>5.2.0-deploy</strong> 版本專注於模型部署。包括<strong>將訓練好的模型轉換為適用於各種平台（如邊緣設備）的格式</strong>。</p><pre>| 類別   | Docker 版本         | 支援的任務 |<br>|--------|---------------------|------------|<br>| Deploy | 5.2.0-deploy        | visual_changenet, centerpose, classification_pyt, classification_tf1, classification_tf2, deformable_detr, detectnet_v2, dino, dssd, efficientdet_tf1, efficientdet_tf2, faster_rcnn, lprnet, mask_rcnn, ml_recog, multitask_classification, ocdnet, ocrnet, optical_inspection, retinanet, segformer, ssd, trtexec, unet, yolo_v3, yolo_v4, yolo_v4_tiny |</pre><h3>9.2 設定環境變量(容器名稱、版本、路徑)</h3><p>根據要訓練的模型，必須拉取對應的容器。以下我們以<strong>classification_tf1</strong>這個任務為例，選擇docker 5.0.0-tf1.15.5 ,在 ubuntu中輸入以下指令:</p><pre>export DOCKER_REGISTRY=&quot;nvcr.io&quot;<br>export DOCKER_NAME=&quot;nvidia/tao/tao-toolkit&quot;<br>export DOCKER_TAG=&quot;5.0.0-tf1.15.5&quot; ## for TensorFlow docker<br>export DOCKER_CONTAINER=$DOCKER_REGISTRY/$DOCKER_NAME:$DOCKER_TAG</pre><p>在ubuntu中可以直接調用docker容器進行模型訓練，初次拉取模型會花較長的時間，在此拉取docker的好處是可以避免進入notebook時可能發生卡住的情況，以下是拉取 5.0.0-tf1.15.5 並執行訓練的程式碼，你可以依需求拉取其中一個，不須全部執行。</p><pre>docker pull nvcr.io/nvidia/tao/tao-toolkit:5.0.0-tf1.15.5<br>docker pull nvcr.io/nvidia/tao/tao-toolkit:5.2.0.1-pyt1.14.0<br>docker pull nvcr.io/nvidia/tao/tao-toolkit:5.0.0-tf2.11.0<br>docker pull nvcr.io/nvidia/tao/tao-toolkit:5.2.0-pyt2.1.0</pre><p>如果不想進入jupyter notebook訓練模型，也可以直接在此下訓練指令，更多說明參考<a href="https://docs.nvidia.com/tao/tao-toolkit/text/working_with_the_containers.html#working-with-the-containers">此處</a>。</p><pre>docker run -it --rm --gpus all -v /path/in/host:/path/in/docker nvcr.io/nvidia/tao/tao-toolkit:5.0.0-tf1.15.5 classification_tf1 train -e /path/to/experiment/spec.txt -r /path/to/results/dir -k $KEY --gpus 4</pre><pre>docker run -it --rm --gpus all -v /path/in/host:/path/in/docker $DOCKER_CONTAINER \<br>       detectnet_v2 train -e /path/to/experiment/spec.txt -r /path/to/results/dir -k $KEY --gpus 4</pre><p>過程中如果出現以下敘述，代表需要更新顯卡驅動程式，請回到步驟1.4用 Genforce Experience 更新 Windows 的顯卡驅動與 Cuda 版本</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RuFkG-xuazUeKyRQ.png" /></figure><p>更新後可用以下命令查看，除了 NVIDIA-SMI 更新到546.65外，我的 CUDA Version 也從原本的11.6更新到12.3</p><pre>nvidia-smi<br>sudo docker run --rm --runtime=nvidia --gpus all ubuntu nvidia-smi</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CjRFxRK4w1xxzPOW.png" /></figure><h3>十、進入範例notebook</h3><p>安裝 jupyter lab</p><pre>pip install jupyterlab</pre><p>打開 jupyterlab</p><pre>jupyter lab</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P1g4gGsxvj5tCQvz.png" /></figure><p>複製產生的網址後，開一個瀏覽器貼上即可進入Jupyter Lab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5vx98wFLXFgCJDkp.png" /></figure><p>進入以下路徑，準備開始第一個電腦視覺遷移學習任務，你也可以選擇從其他任務開始<br>/getting_started_v5.1.0/notebooks/tao_launcher_starter_kit/classification_tf1/tao_voc/classification.ipynb</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*88GIANw3cngEOF0H.png" /></figure><h3>十一、重新進入</h3><p>下次要重新進入時按照以下順序輸入</p><pre>conda activate launcher<br>sudo service docker start<br>jupyter lab</pre><p>至此我們已可以在本機上使用TAO Toolkit進行遷移學習的模型訓練，有關電腦視覺與其他領域的實際訓練流程，將在日後的文章說明，敬請期待。</p><p>我是Ethan，目前為台灣人工智慧學校AI工程師、大型語言模型實作班講師，工作之餘也持續在開發者社群分享NVIDIA SDK的技術應用。歡迎透過Email與我聯繫: ison0615@gmail.com</p><h3>附錄</h3><p>TAO 安裝參考資源<br><a href="https://docs.nvidia.com/tao/tao-toolkit/index.html">NVIDIA Documentation Home-TAO Toolkit (5.2.0)</a><br><a href="https://docs.nvidia.com/tao/tao-toolkit/text/tao_toolkit_quick_start_guide.html#running-tao-toolkit-apis">TAO Toolkit Quick Start Guide</a><br><a href="https://docs.nvidia.com/tao/tao-toolkit/text/troubleshooting_guide.html">Troubleshooting Guide</a><br><a href="https://docs.nvidia.com/tao/tao-toolkit/text/tao_launcher.html#running-the-launcher">TAO Toolkit Launcher</a><br><a href="https://docs.nvidia.com/tao/tao-toolkit/text/working_with_the_containers.html">Working With the Containers</a><br><a href="https://docs.nvidia.com/tao/tao-toolkit/text/running_in_cloud/running_tao_toolkit_on_google_colab.html#id1">Running TAO Toolkit on Google Colab</a><br><a href="http://nvidia.zhidx.com/content-6-3053.html">使用 NVIDIA TAO Toolkit 5.0 體驗最新的視覺 AI 模型開發工作流程</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef647bc32c98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[以 Jetson Xavier NX實現水質桿菌即時偵測、辨識]]></title>
            <link>https://medium.com/@ethankuo_74456/%E4%BB%A5-jetson-xavier-nx%E5%AF%A6%E7%8F%BE%E6%B0%B4%E8%B3%AA%E6%A1%BF%E8%8F%8C%E5%8D%B3%E6%99%82%E5%81%B5%E6%B8%AC-%E8%BE%A8%E8%AD%98%E7%B3%BB%E7%B5%B1-9cd4a805d4a0?source=rss-67d1ee087263------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cd4a805d4a0</guid>
            <category><![CDATA[edge-ai]]></category>
            <dc:creator><![CDATA[Ethan Kuo]]></dc:creator>
            <pubDate>Thu, 08 Sep 2022 17:52:56 GMT</pubDate>
            <atom:updated>2024-06-11T08:42:50.288Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*Vrwl40kLVdTjrQ9Y-euT3Q.png" /></figure><p>2022 年，我與 <a href="https://www.met-ai.net/">MetAI(宇見智能) </a>合力創建了一個對水質桿菌即時偵測、辨識的專案，並參與由資策會創生處與NVIDIA舉辦的Jetson Family微競賽獲得優勝，在這篇文章中我們將解析所有開發的環節。</p><p><strong>一、專案動機</strong></p><p>水質中常見的桿菌有大腸桿菌、腸桿菌、綠膿桿菌等，檢測水質中的桿菌是否超標，常見流程是將取樣後的樣本送進培養皿，需花費24~48小時才能判定。本專案期望運用Jetson Xavier NX 進行水質桿菌即時偵測、辨識，進一步計算桿菌面積占比，期望提供給檢測人員，縮短超標檢測所需時間。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTz7J1vIUkBTP6tDRxYZiQ.png" /><figcaption>圖1: 專案目標</figcaption></figure><p><strong>二、擬定問題解決架構</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdGtskXOVpDdWXSYhDp7PQ.png" /><figcaption>圖2: 問題解決架構</figcaption></figure><p><strong>三、資料收集與標註</strong></p><p><strong>1. 微生物影片收集器材架設</strong></p><p>使用學校生物實驗室之雙筒解剖顯微鏡，放大倍率為600X(目鏡10X、物鏡60X)，以自拍棒將Iphone10的手機鏡頭貼近顯微鏡目鏡鏡頭後開啟錄影，可錄製顯微鏡下成像的影片。由於在學校教室進行，另以袋子罩住鏡頭隔絕週遭光線，避免反光。(編按: 若使用其他錄影設備，錄製時須注意攝影鏡頭直徑須小於目鏡鏡頭)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jglAZUw2qakiqIoJDplow.png" /><figcaption>圖3 : 資料收集設備及實際錄製情景</figcaption></figure><p><strong>2. 以負染色法凸顯桿菌</strong></p><p><strong>負染色法</strong>（Negative stain）是一種染色方法，常用於不透光液體標本的鏡檢。由於其染色處理過程並非針對菌體本身，故又稱「<strong>襯托染色法</strong>」、「<strong>間接染色法</strong>」。在負染色法中，標本不需要熱固定，細胞不會因為化學藥物的影響而變形，對於不易染色的細菌或病毒也能觀察。</p><p>負染色法需要使用酸性染料來染色，如<a href="https://zh.m.wikipedia.org/wiki/%E4%BC%8A%E7%BA%A2">伊紅</a>(Eosin)或<a href="https://zh.m.wikipedia.org/w/index.php?title=%E8%8B%AF%E8%83%BA%E9%BB%91&amp;action=edit&amp;redlink=1">苯胺黑</a>（<a href="https://en.wikipedia.org/wiki/Nigrosin">Nigrosin</a>）。因為細菌體表面(細胞壁)帶負電，而酸性染料的色原也帶負電，所以色原只能將背景染色，才能使細菌很容易的被觀察到。經比較價格後苯胺黑較伊紅昂貴許多，因此團隊購置<a href="https://zh.m.wikipedia.org/wiki/%E4%BC%8A%E7%BA%A2">伊紅</a>(Eosin)為染劑。</p><p><strong>3. 錄製桿菌活動影片並轉換為照片</strong></p><p>常見的大腸桿菌 長(高)為1.5 um，寬(直徑)為0.5–1.0 um，600X的顯微鏡下是合適的視野大小，適度調整顯微鏡光圈、細調節輪後，即可看見桿菌在視野中扭動。</p><p>我們以室溫下靜置30分鐘的鮮乳為檢測樣本，取一滴牛奶滴於載玻片上，加入染劑伊紅(Eosin)將樣本背景染色後蓋上蓋玻片並以顯微鏡觀測，欲觀測的桿菌呈現白色，如下圖:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*euWt4lgI0dikvZHSTikNPw.png" /><figcaption>圖 4 :經伊紅染色後的視野，可辨識出白色桿菌</figcaption></figure><p>團隊在採集多次樣本，錄製不同桿菌活動影片後，以程式將影片每隔五楨取一張圖片，每1分鐘的影片可擷取出300多張圖片。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSZzozxm04QSx0eZx-MY1Q.png" /><figcaption>圖5: 將影片每隔五楨取一楨圖片</figcaption></figure><p><strong>4. 以Label-studio標註桿菌</strong></p><p>我們使用 Label Studio 這款開源資料標註平台，在電腦創建虛擬環境後，安裝所需使用的package，依照以下步驟即可開啟Label Studio的標註介面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yd4TijGlAhpcffbkxS9sCQ.png" /><figcaption>圖6:安裝、開啟 Label-studio 開源資料標註平台</figcaption></figure><p>Label Studio 提供多種資料標註的方式，在此我們選擇 Computer Vision中的 Semantic Segmentation with Masks 方法，對蒐集的桿菌圖片進行標註，產生圖片對應的遮罩，用以訓練深度學習模型。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1PNLxNeimTab01pF45PeA.png" /><figcaption>圖7: Label Studio 提供豐富的資料標註工具</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*MzpDz5OScjJ8hbffcrjSrg.png" /><figcaption>圖8 : 將桿菌以筆刷標註，並會自動產生對應遮罩</figcaption></figure><p><strong>四、電腦視覺模型訓練及優化</strong></p><p><strong>1. NVIDIA TAO Toolkit</strong></p><p><a href="https://developer.nvidia.com/tao-toolkit">NVIDIA TAO Toolkit</a> 是一個遷移學習工具包，包含許多熱門的 AI 預訓練模型，包含電腦視覺與對話式 AI，在語義分割的架構下，我們使用UNET來進行遷移學習。預訓練模型的權重是使用 Google OpenImages 數據集訓練後的結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LJ4jgBXde-ccN7Qg5i8yg.png" /><figcaption><em>圖 9：NVIDIA TAO Toolkit 預訓練模型種類豐富，涵蓋主流電腦視覺任務</em></figcaption></figure><p>TAO-Toolkit 最大的優點就是 low-code 甚至 no-code 的體驗，大幅加速專案開發的效率且降低開發的門檻。</p><p><strong>2. 電腦視覺模型訓練及優化</strong></p><p>除了使用 Tao-Toolkit 訓練模型以外，我們也用原生的 Tensorflow 搭配 CPU 訓練模型，比較硬體與兩個 AI 框架之間搭配的效率差異。以下是我們的訓練比較結果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*JzencLV7sYQpQTvErU-n6w.png" /><figcaption>若以模型訓練參數之數量與需要的訓練時間來做比較，<strong><em>使用 NVIDIA GPU 搭配 Tao-Toolkit 的訓練效率至少可達到使用 Tensorflow 搭配頂級筆電用 CPU 的 1500 % 以上</em></strong>。</figcaption></figure><p><strong>3. 模型再訓練與匯出</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_E-mhwchLgo5I9nGkpDNw.png" /></figure><p>我們採用表現最好的一組模型作為後續的基準，並且準備將模型佈署至邊緣裝置上進行推論。Tao-Toolkit 不僅是 AI 模型訓練框架，更是面向佈署目的而生，訓練完畢的模型可透過量化、剪枝的操作有效縮小模型的尺寸，下為經過 Tao-Toolkit 剪枝後的參數量差異：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*8ju59XdpV8eaKNHTI4zGGg.png" /><figcaption>經過剪枝的模型，移除了大量冗餘的參數，模型的參數量減為將近原本的一半，使得運算速度快上將近一倍。</figcaption></figure><p><strong>五、將模型佈署於Jetson Xavier NX進行推論</strong></p><p>本專案使用的推論硬體為邊緣運算裝置 NVIDIA Jetson Xavier NX ，其為小尺寸模組系統 (SOM)，但卻具備高達 21 兆次運算的加速運算，可提供足夠效能。此外，Jetson Xavier NX 模組具備雲端原生支援，開發人員能夠將訓練後的模型以容器化方式部署至 Jetson 裝置。在加速 NVIDIA 應用軟體堆疊方面，Jetson Xavier NX 的效能比起獲得廣泛採用的前一代產品 Jetson TX2 高出 10 倍。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9C8t3qUIndeCzuQIKuunsA@2x.jpeg" /><figcaption>NVIDIA Jetson Xavier NX</figcaption></figure><ol><li><strong>在 Jetson Xavier NX 上產生優化的 TensorRT 引擎</strong></li></ol><p>透過 NVIDIA TAO Toolkit 產生的預訓練模型，可以通過 tao-converter 工具轉換成 TensorRT 最佳化推論引擎，TensorRT 引擎可以運行於 x86 和 Jetson 平台，同時在轉換過程當中也可以將模型轉化為較較低的精度如：FP16 與 INT8。</p><p>在 Xavier NX 上以 tao-converter 進行 TensorRT 引擎轉換所需的時間如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*ldTBRCPNdWw6dmGlqYEX8w.png" /></figure><p><strong>2. TensorRT 產生即時推論</strong></p><p>不同於過往的 Jetpack 版本，在 Jetpack 4.6 後的所有版本都已經內建有 TensorRT、CUDA、CUDNN 等等過去需要手動安裝的套件，因此只需要使用已經內建的 TensorRT Python SDK 進行推論即可。以下是使用 TensorRT 進行推論的效率，完全滿足此應用的 real-time 要求。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*EnNuWnVmMIXqDE3GXnns4Q.png" /></figure><p><strong>3. 實際推論結果影片</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FggVLWoQzFNY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DggVLWoQzFNY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FggVLWoQzFNY%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/5591aa9ae41d3faf2ea48a7b4f861394/href">https://medium.com/media/5591aa9ae41d3faf2ea48a7b4f861394/href</a></iframe><p><strong>4.判斷桿菌比例是否超出標準</strong></p><p>參照政府訂定的標準，飲用水水質桿菌群的超標限度為：66（CFU/100 毫升），其中<a href="https://www.superlab.com.tw/cfu-mpn/">CFU單位</a>(Colony-forming unit)，是以平板固態培養基滋長細菌後，實際統計的真實菌落數，其預設每個菌落皆由單一隻細菌繁殖形成。而滴定管每滴溶液為1/20毫升，換算下來的標準為每滴飲用水不得超過3/1000隻大腸桿菌。</p><p>將牛奶搖勻後(或用離心機使濃度均勻)，混合染劑伊紅，並取一滴溶液滴於載玻片上，使用長、寬均為2公分的正方形蓋玻片能將液體均勻覆蓋，因此我們以每張蓋玻片中桿菌不得超過3/1000隻為標準推算面積占比。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*14X7dV16xwGXbXoafg4Bpw.png" /></figure><p>P.S.這是因為我們使用已接近壞掉的牛奶來做檢測的結果，一般從超商買回來的健康飲品，在視野下是看不到桿菌的。</p><p><strong>六、結語&amp;展望</strong></p><p>本次專案是產、官、學合作的極佳詮釋，感謝資策會創生處、NVIDIA 協同舉辦Jetson Family 微競賽，讓高中生能運用 NVIDIA 的資源開發出end-to-end的專案。過程中也感謝宇見智能的諸多協助。這次參賽經驗也轉化為高中AI的教學素材，在產業AI化的時代下，也能讓AI教育持續向下紮根。也歡迎對本專案或AI產學合作有興趣的讀者來信交流(ison0615<a href="/service/mailto:ethankuo@gm.nssh.ntpc.edu.tw">@gma</a>il.com)。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cd4a805d4a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>