<?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 Albert Chen on Medium]]></title>
        <description><![CDATA[Stories by Albert Chen on Medium]]></description>
        <link>https://medium.com/@albertchen3389?source=rss-def57b3cef02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Upom9kz685saFnvPTg8tGw.jpeg</url>
            <title>Stories by Albert Chen on Medium</title>
            <link>https://medium.com/@albertchen3389?source=rss-def57b3cef02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:19:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@albertchen3389/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[如何在 Google Colab 上部署 Gemma-2–27b 以開發中文 NLP 應用]]></title>
            <link>https://medium.com/@albertchen3389/%E5%A6%82%E4%BD%95%E5%9C%A8-google-colab-%E4%B8%8A%E9%83%A8%E7%BD%B2-gemma-2-27b-%E4%BB%A5%E9%96%8B%E7%99%BC%E4%B8%AD%E6%96%87-nlp-%E6%87%89%E7%94%A8-47e6e8562aee?source=rss-def57b3cef02------2</link>
            <guid isPermaLink="false">https://medium.com/p/47e6e8562aee</guid>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gemma2]]></category>
            <category><![CDATA[中文自然語言處理]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Albert Chen]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 12:25:55 GMT</pubDate>
            <atom:updated>2024-12-06T07:15:29.252Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Gemma-2？</h3><p>Gemma 2 是 Google 開發的最新開源大型語言模型 (SOTA Open 模型) ，讓我們可以直接取得模型權重，從而開發各種文字生成的應用（需符合<a href="https://ai.google.dev/gemma/terms">授權</a>規範），例如回答問題、摘要和廣告文案撰寫；或使用自有的特定領域語料進行微調訓練。Gemma-2 採用了 Decoder Only 的 Transformer 架構，具有相對較小的模型參數量，因此能夠在資源有限的環境中運行，例如： 筆記型電腦、桌上型電腦或自有雲端基礎架構。</p><p>Gemma 2 提供三種模型，參數大小分別為 20 億、90 億和 270 億，且能在單一 GPU 上運行。其性能相當於參數量是其兩倍或更多的其它模型，非常具有競爭力。對於其模型架構細節(例如 <em>Group Query Attention</em> 機制）感興趣的讀者可以參考<a href="https://amaarora.github.io/posts/2024-07-07%20Gemma.html">這篇</a>技術文章。</p><p>本文將由應用的角度出發，與大家分享如何在 Colab 上搭配 A100 這樣的 GPU ，無痛開發中文 NLP 應用，我們將會以 Step by Step 的方式，從環境建置到程式開發進行詳細介紹，幫助讀者在資源受限的情況下，順利體驗大型語言模型的強大功能。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iLW6T8eRYhtBlaAa" /></figure><h3>使用 Colab 的好處</h3><p>最近在 <a href="https://devfest-taipei.gdg.tw/2024/schedule">DevFest Taipei 2024 </a>聽到<a href="https://devfest-taipei.gdg.tw/2024/schedule/769073">魏澤人</a>老師推薦在 Colab 上運行大型語言模型，促使我嘗試在 Colab 上使用 Google 新推出的 Gemma-2。 傳統上，開發 LLM 或深度學習應用需要連線到專用的 GPU 伺服器，這通常涉及以下幾個痛點：</p><ol><li><strong>複雜的設置流程</strong><br>為了在 GPU 伺服器上開發，我們需要架設 Jupyter Notebook 或 Code Server，這不僅耗時，還需要具備網路服務的相關知識。例如，必須手動配置防火牆，而 Jupyter Notebook 的功能也有點陽春。</li><li><strong>高昂的硬體成本與維護</strong><br>大型語言模型的檔案通常非常龐大，單個模型可能佔用數十 GB 的儲存空間。像我同測試多種模型時，SSD 塞滿了多個模型檔，常要刪掉不常用的模型檔以釋放 SSD 空間。</li><li><strong>有限的開發靈活性</strong><br>使用專用 GPU 伺服器意味著開發者必須依賴特定的硬體配置，若硬體資源不足，將嚴重影響開發效率。此外，遠端連接的網路穩定性和速度也可能成為瓶頸，影響開發體驗，像我自已常會遇到 GPU 工作站重開機後 <a href="https://medium.com/@yt.chen/nvidia-smi-%E9%80%A3%E4%B8%8D%E5%88%B0-driver-%E7%9A%84%E8%87%AA%E6%95%91%E6%96%B9%E6%B3%95-69cbed16171d">NDIVIA Driver 掛掉</a>的問題，似乎是因為 Ubuntu 在重開機時會自動安裝新版的 Kernel，造成新版 Kernel 和原有的 Driver 不相容，所以有穩定的 GPU 環境對 Linux 系統也有一定的熟悉度。</li></ol><p>相比之下，使用 Google Colab 運行大型語言模型具以下優點：</p><ul><li><strong>節省本機儲存空間</strong><br>巨大的模型檔可以直接存放在 Google Drive 中，不佔用本機端的硬碟空間。這對於需要同時測試多種大型語言模型的開發者來說，極具吸引力。</li><li><strong>高效且經濟的硬體資源</strong><br>只需支付少量費用，即可使用擁有 40G 記憶體的 A100 GPU，支持參數量極大的模型，如 27B 版本的 Gemma-2。這大大降低了硬體投資成本，並提升了運算效能。</li><li><strong>靈活的開發環境</strong><br>只要有一台筆電並能連上網路，即可在 Colab 上進行開發與展示大型語言模型的應用，無需依賴專用的 GPU 伺服器。這不僅提高了開發的靈活性，也讓遠端協作變得更加簡單。</li></ul><h3>如何在 Google Colab 上配置、運行 27B 模型與開發中文 NLP應用</h3><p>以下為 step by step 的介紹：</p><ol><li>在 Google Drive 建立模型資料夾</li></ol><p>首先，前往你的 Google Drive，建立一個專門用來存放模型檔案的資料夾。例如，可以命名為 Large_models。</p><p>2. 在 Colab 連結 Google Drive<br>在 Google Colab 中運行以下程式，將你的 Google Drive 掛載到 Colab 的運算環境</p><pre>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)</pre><p>3. 連結 Google Drive 的模型目錄到 Colab 環境</p><p>接下來，將你在 Google Drive 中建立的 Large_models 資料夾連結到 Colab 的運算環境中，例如連結到 /root/.models</p><pre>!ln -s &#39;/content/drive/MyDrive/Large_models/&#39; /root/.models</pre><p>完成後，可以使用 ls 指令檢查連結是否成功，確認 /root/.models/ 目錄下是否能看到 Google Drive 中的檔案。如下圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZVCuRjgqRlbDCG0VlAb3w.png" /></figure><p>4. 設定 HuggingFace 套件的 Home 目錄與登入 Hugginfface</p><p>為了確保下載的模型檔案儲存在 Google Drive 中，而非 Colab 的臨時運算環境，需設定 HuggingFace 套件的 Home 目錄：</p><pre>%env HF_HOME=/root/.models</pre><p>輸入登入 hugginfface 的 token，因為 Gemma 2 是要接受授權條款才能使用的開源模型。</p><pre>from huggingface_hub import notebook_login<br><br>notebook_login()</pre><p>5. 安裝套件</p><p>要以 4-bit 等省計憶體的方式載入大型模型，需要裝 bitsandbytes 與accelerate。此外，我強力推薦使用 <a href="https://github.com/huggingface/local-gemma">local_gemma</a> 套件，它能簡化在 GPU 記憶體有限的情況下載入大型語言模型所需的多項設定，如量化設定。local_gemma 提供多種預設選項 (如： exact, speed, memory, memory_extreme)，它會自動的產生 bitsandbytes、accelerate 套件所需的配置。甚至當你選用 &quot;auto” 選項時，此套件還會依據你的硬體環境，自動選擇最佳配置，減少記憶體不足的錯誤，因為它可利用 CPU Offload 技術來最大化記億體的使用效率。由下表可知 24G 的 GPU 要使用 27B 模型是可行的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gMtBD6pZRl8EZllWrMB3w.png" /><figcaption>local_gemma</figcaption></figure><p>以下是安裝指令：</p><pre>!pip install U bitsandbytes accelerate<br>!pip install local_gemma</pre><p>6. 開發中文 NLP 應用</p><p>接下來，我們將測試 Gemma-2–27b 模型的中文 NLP 能力，應用場景為抽取電腦零組件的品牌與型號。</p><h3>範例資料 — 繁體中文文本</h3><p>使用原價屋的報價系統作為範例文本資料：</p><pre>Intel i5-14500【14核/20緒】2.6GHz(↑5G)/24M/UHD770/65W 【代理盒裝】, $7800↘$7700 ◆ ★ 熱賣<br>華碩 PRIME H610M-K D4-CSM(M-ATX/1A1H/Realtek 1Gb/註冊四年/2DIMM)6+1+1相, $2890 ◆ ★ ↓任搭300↓ <br>UMAX 單條16GB DDR5-5600/CL46【雙參數】, $1150 ◆ ★ 熱賣 <br>威剛 Ultimate SU800 256G/2.5吋/讀:560M/寫:520M/TLC/DRAM快取/SMI/台灣製【五年】, $999 ◆ ★ <br>利民 AXP120-X67 下吹式 6導管(6mm)/TL-C12015薄扇/高6.7cm【WXHZ】, $1390 ◆ ★ <br>華碩 DUAL-RTX4070-O12GD6-EVO(2550MHz/23cm/8Pin/雙風扇/註四年), $18990 ◆ ★ ↓任搭100↓ <br>Fractal Design Terra 黑 卡長32.2(厚4.3-7.2)/U高7.7(4.8)/鋁機身/胡桃木面板/ITX【SFX】, $6790 ◆ ★ <br>海韻 FOCUS GX-750(750W) 白色版 雙8/金牌/全模組/10年保, $3490 ◆ ★</pre><h3>使用 LLM 進行文本抽取</h3><p>傳統上，我們可能會使用 Regular Expression 來開發這類抽取功能，但規則複雜且難以維護。利用開源的大型語言模型（LLM）與其 In-Context Learning 能力，只需提供少量範例，即可完成文本抽取任務，且可節省使用閉源 LLM 模型 API 的費用。在實務應用中，通常會結合使用開源與閉源模型，以達到成本效益與智慧表現的最佳平衡。</p><p>7. 載入 Gemma-2–27b 模型</p><p>首先要載入模型檔，這裡使用經過指令微調的模型版本，尾碼是 &quot;it”，preset 選 &quot;memory”：</p><pre>from local_gemma import LocalGemma2ForCausalLM<br>from transformers import AutoTokenizer<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;google/gemma-2-27b-it&quot;)<br>model = LocalGemma2ForCausalLM.from_pretrained(&quot;google/gemma-2-27b-it&quot;, preset=&quot;memory&quot;)</pre><p>執行後，可以看到 A100 GPU 的 Memory 使用了 17,069MB，如下圖。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ottJV8D3qW13w7j6xSOdBA.png" /></figure><p>8.實作中文 NLP 應用範例</p><ul><li>在 prompt template 中，我們僅提供一個抽取範例，以指導 LLM 進行文本抽取，並要求 LLM 以 JSON 格式傳回結構化結果。</li><li>tokenizer.apply_chat_template() 則是用來 產生與 LLM 進行對話時，所需的特殊 tokens ，如：&lt;bos&gt;&lt;start_of_turn&gt;&lt;end_of_turn&gt;，每個 LLM 在訓練對話能力時，都有其自訂的特殊 tokens，所以在此叫用此 function 才會產生適合該 LLM 的特殊 tokens。</li><li>LLM 回傳的結果都是 tokens 的 ID （整數數值），我們需要將其解碼為可讀的文字 （decoded_text）。</li></ul><pre># 定義 prompt 模板<br>template = &quot;&quot;&quot;<br>&lt;prompt&gt;<br>你是專業的電腦零組件專家。<br>請抽取以下電腦零組件產品的名稱，只保留產品的品牌與主要型號，忽略後面的規格描述和附加信息。<br>例如，將&#39;華碩 Pro WS W790E-SAGE SE(EEB/8DDR5/2Intel 10G+Realtek 1Gb)14+1+1功率級&#39; <br>抽取出 &#39;華碩 Pro WS W790E-SAGE SE&#39;<br>請將你的抽取結果使用以下 JSON 格式呈現。<br><br><br>EXAMPLE FORMAT:<br>```json<br>{{<br><br>    &quot;item&quot;: &quot;Your extraction here.&quot;<br><br>}}<br>```<br><br>要分析的文字如下:<br>@@@{product_text}@@@<br>Remember: Output ONLY the JSON analysis, with no additional text.<br>&lt;answer&gt;<br>&quot;&quot;&quot;<br><br><br><br># 要進行抽取的文本<br>product_text = &quot;&quot;&quot;Intel i5-14500【14核/20緒】2.6GHz(↑5G)/24M/UHD770/65W 【代理盒裝】, $7800↘$7700 ◆ ★ 熱賣<br>華碩 PRIME H610M-K D4-CSM(M-ATX/1A1H/Realtek 1Gb/註冊四年/2DIMM)6+1+1相, $2890 ◆ ★ ↓任搭300↓ <br>UMAX 單條16GB DDR5-5600/CL46【雙參數】, $1150 ◆ ★ 熱賣 <br>威剛 Ultimate SU800 256G/2.5吋/讀:560M/寫:520M/TLC/DRAM快取/SMI/台灣製【五年】, $999 ◆ ★ <br>利民 AXP120-X67 下吹式 6導管(6mm)/TL-C12015薄扇/高6.7cm【WXHZ】, $1390 ◆ ★ <br>華碩 DUAL-RTX4070-O12GD6-EVO(2550MHz/23cm/8Pin/雙風扇/註四年), $18990 ◆ ★ ↓任搭100↓ <br>Fractal Design Terra 黑 卡長32.2(厚4.3-7.2)/U高7.7(4.8)/鋁機身/胡桃木面板/ITX【SFX】, $6790 ◆ ★ <br>海韻 FOCUS GX-750(750W) 白色版 雙8/金牌/全模組/10年保, $3490 ◆ ★&quot;&quot;&quot;<br>messages = [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: template.format(product_text=product_text)},<br>  <br>]<br><br>print(f&#39;要抽取的來源：\n{product_text}&#39;)<br>model_inputs = tokenizer.apply_chat_template(messages, return_tensors=&quot;pt&quot;, return_dict=True)<br>prompt_length = model_inputs.input_ids.shape[1]<br><br>generated_ids = model.generate(**model_inputs.to(model.device), max_new_tokens=512, temperature=0.2,<br>    top_p=0.9,<br>    top_k=40,repetition_penalty=1.05, do_sample =True,<br>    eos_token_id=tokenizer.eos_token_id,<br>    pad_token_id=tokenizer.pad_token_id,<br>    num_return_sequences=1,length_penalty=1.0,)<br><br># 解碼結果<br>decoded_text = tokenizer.decode(generated_ids[0][prompt_length:], skip_special_tokens=True)<br>print(decoded_text)</pre><p>程式輸出如下，品項資訊抽取的結果蠻好的！未來可再做更大規模的評測。</p><pre>要抽取的來源：<br>Intel i5-14500【14核/20緒】2.6GHz(↑5G)/24M/UHD770/65W 【代理盒裝】, $7800↘$7700 ◆ ★ 熱賣<br>華碩 PRIME H610M-K D4-CSM(M-ATX/1A1H/Realtek 1Gb/註冊四年/2DIMM)6+1+1相, $2890 ◆ ★ ↓任搭300↓ <br>UMAX 單條16GB DDR5-5600/CL46【雙參數】, $1150 ◆ ★ 熱賣 <br>威剛 Ultimate SU800 256G/2.5吋/讀:560M/寫:520M/TLC/DRAM快取/SMI/台灣製【五年】, $999 ◆ ★ <br>利民 AXP120-X67 下吹式 6導管(6mm)/TL-C12015薄扇/高6.7cm【WXHZ】, $1390 ◆ ★ <br>華碩 DUAL-RTX4070-O12GD6-EVO(2550MHz/23cm/8Pin/雙風扇/註四年), $18990 ◆ ★ ↓任搭100↓ <br>Fractal Design Terra 黑 卡長32.2(厚4.3-7.2)/U高7.7(4.8)/鋁機身/胡桃木面板/ITX【SFX】, $6790 ◆ ★ <br>海韻 FOCUS GX-750(750W) 白色版 雙8/金牌/全模組/10年保, $3490 ◆ ★<br>```json<br>{<br>  &quot;item&quot;: &quot;Intel i5-14500&quot;<br>}<br>```<br><br>```json<br>{<br>  &quot;item&quot;: &quot;華碩 PRIME H610M-K D4-CSM&quot;<br>}<br>```<br><br>```json<br>{<br>  &quot;item&quot;: &quot;UMAX DDR5-5600&quot;<br>}<br>```<br><br>```json<br>{<br>  &quot;item&quot;: &quot;威剛 Ultimate SU800&quot;<br>}<br>```<br><br>```json<br>{<br>  &quot;item&quot;: &quot;利民 AXP120-X67&quot;<br>}<br>```<br><br>```json<br>{<br>  &quot;item&quot;: &quot;華碩 DUAL-RTX4070-O12GD6-EVO&quot;<br>}<br>```<br><br>```json<br>{<br>  &quot;item&quot;: &quot;Fractal Design Terra&quot;<br>}<br>```<br><br>```json<br>{<br>  &quot;item&quot;: &quot;海韻 FOCUS GX-750&quot;<br>}<br>```</pre><h3>結論</h3><p>使用 Google 最新的開源大型語言模型 Gemma-2，降低了開發中文 NLP 應用的進入門檻，展現了大型預訓練語言模型的威力！更重要的是，使得在資源有限的環境中開發和測試這些模型變得更可行。藉由使用 Colab 和如 local_gemma 等套件，我們能夠在不需要昂貴硬體資源的情況下輕鬆開發中文自然語言處理應用，如產品名稱抽取，並充分利用 In-Context Learning 來簡化文本抽取的過程。</p><p>這次的測試顯示，Gemma-2–27b 在硬體資源受限的情況下也能提供不錯的性能，尤其在文本抽取這類需要語言理解的應用上。我們透過簡單的一個範例，即可讓模型完成品牌和型號的識別。</p><p>希望這篇文章能夠為大家展示 Gemma-2 在 Colab 平台上的應用潛力，並鼓勵更多的開發者探索如何在實務中應用大型語言模型來解決各種問題。無論是想要開發原型、測試想法，還是進行小型專案，Colab 提供了一個低成本又有效率的平台，而 Gemma-2 的開源特性更擴展了我們的選擇與自由度，未來我們可以嘗試用自有特定繁體中文語料來微調 27B 模型，或許可以得到更出色的效果！</p><h3>Reference</h3><ul><li>Hugging Face 的 Local_gemma 套件：<a href="https://github.com/huggingface/local-gemma">https://github.com/huggingface/local-gemma</a></li><li>介紹 Gemma 2 模型技術的文章： <a href="https://amaarora.github.io/posts/2024-07-07%20Gemma.html">Gemma 2: Improving Open Language Models at a Practical Size</a></li><li>Gemma 應用的各種案例程式： <a href="https://github.com/google-gemini/gemma-cookbook">Gemma Cookbook</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47e6e8562aee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[從零開始建構一個 LLM Agent]]></title>
            <link>https://medium.com/@albertchen3389/%E5%BE%9E%E9%9B%B6%E9%96%8B%E5%A7%8B%E5%BB%BA%E6%A7%8B%E4%B8%80%E5%80%8B-llm-agent-5e747300c170?source=rss-def57b3cef02------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e747300c170</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Albert Chen]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 14:46:02 GMT</pubDate>
            <atom:updated>2024-12-13T03:43:26.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>一、背景</h3><p>雖然 ChatGPT 等大型語言模型（LLM）已廣泛應用於工作中，但單純的 LLM 技術仍有以下限制：</p><p>● 推理能力有限：LLM 雖擅長文本生成，但在複雜的數學運算及邏輯推理方面表現不佳。例如，它可能無法有效解決質因數分解等進階數學問題。</p><p>● 知識時效性：LLM 的知識來自訓練數據，無法即時更新。例如，2024年之前訓練的模型將缺乏最新的時事資訊。</p><p>● 環境互動受限：LLM 僅能處理文本，無法直接與實體或數位 (digital) 環境互動、收集資訊或執行操作。</p><p>為解決這些限制，LLM Agent 技術因應而生。它結合了推理（Reasoning）和行動（Acting）的 ReAct 框架，讓 Agent 能查詢外部資源、與環境互動，並根據回饋調整行為，而能執行更複雜的任務。</p><h3>二、LLM Agents: Bridging the Gap!</h3><p>LLM Agent 是結合大型語言模型的智慧型 agent 程式，能模擬人類的思考過程並執行特定任務。它的核心功能包括：</p><p>● 推理和行動：透過 ReAct 框架，Agent 能夠思考問題、採取措施、收集資訊並根據結果調整推理方向。其運作包含<strong>思考（Thought）、行動（Action）和觀察（Observation）</strong>三個階段。</p><p>● 長期記憶：Agent 具備儲存和檢索資訊的能力，突破了 LLM 上下文窗口的限制，使其能從過去經驗中學習並持續提升效能。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yoZEwuhjNsqIYZb8M52wlQ.png" /><figcaption>Source: UC Berkeley CS 194/294–196 (LLM Agents) — Lecture 2, Shunyu Yao</figcaption></figure><p>目前市面上已有多框架可用於建立 LLM Agent，如 OpenAI <a href="https://github.com/openai/swarm">Swarm</a>和 LangChain 團隊的 <a href="https://www.langchain.com/langgraph">LangGraph</a>。然而，為了深入理解其運作原理，本文將介紹如何從零開始（from scratch）建構 LLM Agent，不依賴任何現有框架。</p><h3>三、ReAct 模式簡介</h3><h3>1. ReAct 是什麼？</h3><p><strong>ReAct</strong> 是 <strong>Reasoning and Acting</strong> 的縮寫，也就是「推理與行動」的意思。ReAct 模式結合了推理（內部思考）和行動（與環境互動）兩個階段，讓模型能夠在解決問題時，先進行思考，再採取行動，並根據行動的結果（觀察）進行下一步推理，流程如下圖。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*UOlnD5ncsx0NUuil.png" /><figcaption>Reasoning and Acting, source: <a href="https://bluetickconsultants.medium.com/react-integrating-reasoning-and-acting-with-retrieval-augmented-generation-rag-a6c2e869f763">ReAct: Integrating Reasoning and Acting with Retrieval-Augmented Generation (RAG)</a></figcaption></figure><h3>2. ReAct 模式的流程</h3><ol><li><strong>Thought（思考）</strong>：模型內部的推理過程，分析問題、制定計劃。</li><li><strong>Action（行動）</strong>：根據思考結果，採取具體的行動，如調用工具或執行指令。</li><li><strong>Observation（觀察）</strong>：行動後，獲取環境的反饋或結果。</li><li><strong>Loop（循環）</strong>：根據觀察結果，返回思考階段，重複上述過程，直到得到最終答案。</li><li><strong>Answer（答案）</strong>：輸出最終的解決方案或回答。</li></ol><h3><strong>3. 為什麼使用 ReAct 模式？</strong></h3><ul><li><strong>增強推理能力</strong>：讓模型在回答前進行思考，避免直接產生錯誤或不完整的答案。</li><li><strong>結合外部工具</strong>：允許模型在需要時調用外部資源或函數，擴展其能力。</li><li><strong>提高可靠性</strong>：通過明確的步驟，減少模型產生幻覺（hallucination）的機會。</li></ul><h3><strong>4. ReAct 模式中的 PAUSE</strong></h3><p>在 ReAct 模式中，<strong>PAUSE</strong> 是關鍵的一部分。它的功能是：</p><ul><li><strong>流程控制</strong>：讓模型在執行 Action 後暫停，等待外部系統執行該 Action 並返回 Observation。</li><li><strong>避免連續生成</strong>：防止模型在未獲得外部結果前繼續生成內容，確保互動的正確性。</li><li><strong>提示外部系統</strong>：告知外部程式，模型已完成了行動決策，需要執行對應的動作。</li></ul><h3><strong>四 </strong>、<strong>基於 ReACT LLM Agent 的金融業務範例</strong></h3><ul><li><strong>背景業務情境 (Business context) 說明</strong></li></ul><p>在這個範例中，我們假設一位投資者持有一定數量的美金（USD），並且定期關注美元對台幣（TWD）的匯率。投資者的目標是尋找最佳時機將手中的美金兌換成台幣，以獲取最大的匯率收益。</p><ul><li><strong>業務邏輯</strong></li></ul><ol><li><strong>持有美金：</strong>投資者目前持有美金，希望在匯率有利時將其兌換成台幣。</li><li><strong>匯率觀察：</strong></li></ol><ul><li><strong>當前匯率</strong>：美元兌台幣的即時匯率（例如：1 USD = 31.5 TWD）。</li><li><strong>平均匯率</strong>：過去一段時間（如一個月或三個月）的平均匯率（例如：平均匯率為 31.0）。</li></ul><p><strong>3. 決策因素：</strong></p><ul><li><strong>匯率差異</strong>：當前匯率與平均匯率之間的差異。<strong>若當前匯率高於平均匯率，代表現在兌換可以獲得更多的台幣</strong>。</li><li><strong>換匯成本</strong>：考慮手續費、稅費等可能影響最終收益的因素。</li></ul><p><strong>4. 換匯策略</strong>：</p><ul><li><strong>有利時兌換</strong>：當匯率差異顯著且有利時，選擇將美金兌換成台幣。</li><li><strong>持續觀察</strong>：若匯率不理想，則繼續持有美金，等待更好的換匯時機。</li></ul><h3><strong>五、應用在 LLM Agent 中</strong></h3><p>在這個範例中，我們使用 LLM Agent 來模擬投資者的決策過程，Agent 會執行以下步驟：</p><p><strong>Step 1：思考（Thought):</strong></p><ul><li>Agent 認為需要查詢當前匯率，以評估是否適合換匯。</li></ul><p><strong>Step 2：行動（Action):</strong></p><ul><li>調用 get_exchange_rate 行動，獲取 USD/TWD 的當前匯率。</li></ul><p><strong>Step 3：觀察（Observation）:</strong></p><ul><li>接收當前匯率的結果（例如：1 USD = 31.5 TWD）。</li></ul><p><strong>Step 4：思考（Thought):</strong></p><ul><li>Agent 認為需要獲取平均匯率，進一步比較。</li></ul><p><strong>Step 5：行動（Action):</strong></p><ul><li>叫用 get_average_exchange_rate 行動，獲取過去一個月的平均匯率。</li></ul><p><strong>Step 6：觀察（Observation）:</strong></p><ul><li>接收平均匯率的結果（例如：平均匯率為 31.0）。</li></ul><p><strong>Step 7：思考（Thought）:</strong></p><ul><li>Agent 計算匯率差異，判斷當前匯率是否有利。</li></ul><p><strong>Step 8：行動（Action）:</strong></p><ul><li>調用 calculate 行動，計算當前匯率與平均匯率的差值（31.5 - 31.0 = 0.5）。</li></ul><p><strong>Step 9：觀察（Observation）:</strong></p><ul><li>接收計算結果（匯率差異為 0.5）。</li></ul><p><strong>Step 10：答案（Answer）</strong></p><ul><li>Agent 根據分析結果，建議投資者現在是換匯的好時機，因為當前匯率高於平均匯率。</li></ul><h3>Code</h3><pre>import openai<br>import re<br>import httpx<br>import os<br>from dotenv import load_dotenv<br><br>_ = load_dotenv() # 使用 dotenv 載入 .env 文件中的環境變數<br>from openai import OpenAI<br><br>client = OpenAI()</pre><pre># 定義 Agent 類別<br>class Agent:<br>    def __init__(self, system=&quot;&quot;):<br>        self.system = system<br>        self.messages = []<br>        if self.system:<br>            self.messages.append({&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system})<br><br>    def __call__(self, message):<br>        self.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message})<br>        result = self.execute()<br>        self.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: result})<br>        return result<br>        # __call__ 方法：當對 Agent instance 叫用時，<br>        # 將 User 的輸入加到 message list，然後調用 execute 方法獲得模型的回應，<br>        # 並將回應加到 message list中，最後返回結果。<br><br>    def execute(self):<br>        completion = client.chat.completions.create(<br>                        model=&quot;gpt-4&quot;, <br>                        temperature=0,<br>                        messages=self.messages)<br>        return completion.choices[0].message.content</pre><pre><br><br>action_re = re.compile(r&#39;^Action: (\w+): (.*)&#39;)<br><br># 定義可用的行動函數<br>def get_exchange_rate(currency_pair):<br>    # 模擬獲取當前匯率，實際應該調用外部 API<br>    exchange_rates = {<br>        &quot;USD/TWD&quot;: 31.5,  # 假設當前匯率為 31.5<br>    }<br>    rate = exchange_rates.get(currency_pair.strip(), None)<br>    if rate:<br>        return f&quot;The current exchange rate for {currency_pair} is {rate}&quot;<br>    else:<br>        return f&quot;Exchange rate for {currency_pair} is not available&quot;<br><br>def get_average_exchange_rate(currency_pair, period=&quot;1 month&quot;):<br>    # 模擬獲取平均匯率，實際應該調用外部 API 或資料庫<br>    average_rates = {<br>        (&quot;USD/TWD&quot;, &quot;1 month&quot;): 31.0,<br>        (&quot;USD/TWD&quot;, &quot;3 months&quot;): 30.8,<br>    }<br>    rate = average_rates.get((currency_pair.strip(), period.strip()), None)<br>    if rate:<br>        return f&quot;The average exchange rate for {currency_pair} over {period} is {rate}&quot;<br>    else:<br>        return f&quot;Average exchange rate for {currency_pair} over {period} is not available&quot;<br><br>def calculate(expression):<br>    try:<br>        return str(eval(expression))<br>    except Exception as e:<br>        return f&quot;Calculation error: {e}&quot;<br><br># 定義已知的行動<br>known_actions = {<br>    &quot;get_exchange_rate&quot;: get_exchange_rate,<br>    &quot;get_average_exchange_rate&quot;: get_average_exchange_rate,<br>    &quot;calculate&quot;: calculate<br>}<br><br># 定義 Prompt<br>prompt = &quot;&quot;&quot;<br>You run in a loop of Thought, Action, PAUSE, Observation.<br>At the end of the loop you output an Answer.<br><br>Use Thought to describe your thoughts about the question you have been asked.<br>Use Action to run one of the actions available to you - then return PAUSE.<br>Observation will be the result of running those actions.<br><br>Your available actions are:<br><br>get_exchange_rate:<br>e.g. get_exchange_rate: USD/TWD<br>Gets the current exchange rate for the given currency pair.<br><br>get_average_exchange_rate:<br>e.g. get_average_exchange_rate: USD/TWD, 1 month<br>Gets the average exchange rate for the given currency pair over a specified period.<br><br>calculate:<br>e.g. calculate: 4 * 7 / 3<br>Runs a calculation and returns the number.<br><br>Example session:<br><br>Question: Should I exchange my USD to TWD this month considering the average exchange rate?<br>Thought: I need to check the current exchange rate for USD to TWD.<br>Action: get_exchange_rate: USD/TWD<br>PAUSE<br><br>You will be called again with this:<br><br>Observation: The current exchange rate for USD/TWD is 31.5<br><br>You then output:<br><br>Thought: I should compare the current exchange rate with the average exchange rate over the past month.<br>Action: get_average_exchange_rate: USD/TWD, 1 month<br>PAUSE<br><br>You will be called again with this:<br><br>Observation: The average exchange rate for USD/TWD over 1 month is 31.0<br><br>You then output:<br><br>Thought: The current rate is higher than the average by 0.5. It might be a good time to exchange.<br>Action: calculate: 31.5 - 31.0<br>PAUSE<br><br>You will be called again with this:<br><br>Observation: 0.5<br><br>You then output:<br><br>Answer: Yes, considering the current exchange rate is higher than the average by 0.5, it is a good time to exchange your USD to TWD.<br>&quot;&quot;&quot;.strip()<br><br># 定義 Main function<br>def query(question, max_turns=10):<br>    i = 0<br>    bot = Agent(prompt)<br>    next_prompt = question<br>    while i &lt; max_turns:<br>        i += 1<br>        result = bot(next_prompt)<br>        print(result)<br>        actions = [<br>            action_re.match(a)<br>            for a in result.split(&#39;\n&#39;)<br>            if action_re.match(a)<br>        ]<br>        if actions:<br>            # 有行動需要執行<br>            action_match = actions[0]<br>            action, action_input = action_match.groups()<br>            if action not in known_actions:<br>                raise Exception(f&quot;Unknown action: {action}: {action_input}&quot;)<br>            print(f&quot; -- running {action} {action_input}&quot;)<br>            if action == &quot;get_average_exchange_rate&quot;:<br>                # 處理多個參數<br>                params = action_input.split(&#39;,&#39;)<br>                observation = known_actions[action](*params)<br>            else:<br>                observation = known_actions[action](action_input.strip())<br>            print(&quot;Observation:&quot;, observation)<br>            next_prompt = f&quot;Observation: {observation}&quot;<br>        else:<br>            # 無行動，對話結束<br>            return<br><br># 執行查詢<br>question = &quot;Should I exchange my USD to TWD this month considering the average exchange rate?&quot;<br>query(question)</pre><h3>Code Output</h3><p>當我們執行 query 函數時，流程如下：</p><ol><li><strong>第一輪</strong>：</li></ol><ul><li><strong>用戶輸入</strong>：&quot;Should I exchange my USD to TWD this month considering the average exchange rate?&quot;</li><li><strong>模型輸出</strong>：</li></ul><pre>Thought: I need to check the current exchange rate for USD to TWD.<br>Action: get_exchange_rate: USD/TWD<br>PAUSE</pre><ul><li><strong>執行行動</strong>：get_exchange_rate(&quot;USD/TWD&quot;)</li><li><strong>觀察結果</strong>：&quot;The current exchange rate for USD/TWD is 31.5&quot;</li><li><strong>更新輸入</strong>：&quot;Observation: The current exchange rate for USD/TWD is 31.5&quot;</li></ul><p><strong>第二輪</strong>：</p><ul><li><strong>模型輸出</strong></li></ul><pre>Thought: I should compare the current exchange rate with the average exchange rate over the past month.<br>Action: get_average_exchange_rate: USD/TWD, 1 month<br>PAUSE</pre><ul><li><strong>執行行動</strong>：get_average_exchange_rate(&quot;USD/TWD&quot;, &quot;1 month&quot;)</li><li><strong>觀察結果</strong>：&quot;The average exchange rate for USD/TWD over 1 month is 31.0&quot;</li><li><strong>更新輸入</strong>：&quot;Observation: The average exchange rate for USD/TWD over 1 month is 31.0&quot;</li></ul><p><strong>第三輪</strong>：</p><ul><li><strong>模型輸出</strong>：</li></ul><pre>Thought: The current rate is higher than the average by 0.5. It might be a good time to exchange.<br>Action: calculate: 31.5 - 31.0<br>PAUSE</pre><ul><li><strong>執行行動</strong>：calculate(&quot;31.5 - 31.0&quot;)</li><li><strong>觀察結果</strong>：&quot;0.5&quot;</li><li><strong>更新輸入</strong>：&quot;Observation: 0.5&quot;</li></ul><p><strong>第四輪</strong>：</p><ul><li><strong>模型輸出</strong>：</li></ul><pre>Thought: The difference is 0.5, indicating the current rate is favorable.<br>Answer: Yes, considering the current exchange rate is higher than the average by 0.5, it is a good time to exchange your USD to TWD.</pre><ul><li>沒有新的行動，對話結束。</li></ul><h3>完整 code 輸出如下：</h3><pre>Thought: I need to check the current exchange rate for USD to TWD.<br>Action: get_exchange_rate: USD/TWD<br>PAUSE<br> -- running get_exchange_rate USD/TWD<br>Observation: The current exchange rate for USD/TWD is 31.5<br>Thought: I should compare the current exchange rate with the average exchange rate over the past month.<br>Action: get_average_exchange_rate: USD/TWD, 1 month<br>PAUSE<br> -- running get_average_exchange_rate USD/TWD, 1 month<br>Observation: The average exchange rate for USD/TWD over  1 month is 31.0<br>Thought: The current rate is higher than the average by 0.5. It might be a good time to exchange.<br>Action: calculate: 31.5 - 31.0<br>PAUSE<br> -- running calculate 31.5 - 31.0<br>Observation: 0.5<br>Answer: Yes, considering the current exchange rate is higher than the average by 0.5, it is a good time to exchange your USD to TWD.</pre><h3><strong>六</strong>、<strong>結論</strong></h3><p>透過本篇文章，我們從零開始建構了一個不依賴任何框架的 LLM Agent，並了解了 ReAct 模式的運作方式。藉由金融業務的範例，我們展示了如何結合思考、行動和觀察，讓 Agent 模擬人類的決策過程。希望讀者在閱讀後，能夠對 LLM Agent 的概念有更深入的理解，並將這些知識應用到實際的專案中，發揮大型語言模型的強大能力，而對 LLM Agent 有興趣做更深入了解的讀者可以閱讀這篇 <a href="https://lilianweng.github.io/posts/2023-06-23-agent/">LLM Powered Autonomous Agents</a>，有更詳細的介紹。</p><h3>Reference</h3><ul><li><a href="https://bluetickconsultants.medium.com/react-integrating-reasoning-and-acting-with-retrieval-augmented-generation-rag-a6c2e869f763">ReAct: Integrating Reasoning and Acting with Retrieval-Augmented Generation (RAG)</a></li><li>學習資源 MOOC: <a href="https://llmagents-learning.org/f24">Large Language Model Agents</a></li><li>學習資源 DeepLearning.AI course: <a href="https://www.deeplearning.ai/short-courses/ai-agents-in-langgraph/">AI Agents in LangGraph</a></li><li>LLM Agent 好文推薦：<a href="https://lilianweng.github.io/posts/2023-06-23-agent/">LLM Powered Autonomous Agents</a></li><li>Video 解說：<a href="https://www.bilibili.com/video/BV1ju4y1e7Em/">姚顺雨-从语言模型到语言智能体（From Language Models to Language Agents）</a></li><li>Paper: <a href="https://arxiv.org/abs/2210.03629">ReAct: Synergizing Reasoning and Acting in Language Models</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e747300c170" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Computing for Training Large Models with AWS SageMaker]]></title>
            <link>https://medium.com/@albertchen3389/distributed-computing-for-training-large-models-with-aws-sagemaker-ad0500d23368?source=rss-def57b3cef02------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad0500d23368</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[distributed-training]]></category>
            <dc:creator><![CDATA[Albert Chen]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 10:17:51 GMT</pubDate>
            <atom:updated>2024-04-24T06:26:47.443Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Today’s deep learning models, such as large language models (LLMs), demand training on vast datasets and can encompass billions of parameters. This magnitude of data introduces formidable challenges, particularly regarding the extensive training time required. To tackle these issues, a highly efficient and robust infrastructure is essential. Cloud platforms like AWS SageMaker provide such an infrastructure, equipping developers with the tools to effectively surmount these training hurdles.</p><h3>Model Development and Training Process</h3><h3>Development Phase</h3><p>At the outset of our model’s lifecycle, we prioritize rapid iterations and continuous enhancements. For this, we engage cost-effective compute resources, notably the AWS SageMaker’s <strong><em>Notebook Instances</em></strong>. These platforms furnish us with an intuitive Jupyter Notebook interface that facilitates swift and agile development.</p><p>As the model matures and its intricacies unfold, we elevate our training to robust compute instances. These powerhouses are adept at managing voluminous datasets and rigorous computational tasks. Our Jupyter notebooks are the nerve center from which we direct our training jobs, subsequently executed by these potent compute instances. This strategy streamlines our workflow and guarantees judicious resource allocation.</p><p>Here’s how it unfolds in AWS:</p><p>To initiate the training sequence, you need a well-crafted notebook and a train.py script. Within the notebook&#39;s milieu, employ the command below to trigger your training job. Your data should be accessible in an S3 bucket or FSx within the AWS region selected for the training execution. If utilizing SageMaker’s Jupyter notebooks, it&#39;s imperative to have your notebook instance in the same region as your data repository.</p><pre>from sagemaker.pytorch import PyTorch<br><br>estimator = PyTorch(<br>    base_job_name=&quot;pytorch-smdataparallel-large-model&quot;,<br>    source_dir=&quot;code&quot;,<br>    entry_point=&quot;train.py&quot;,<br>    role=role,<br>    framework_version=&quot;2.0.1&quot;,<br>    py_version=&quot;py38&quot;,<br>    # For training with multinode distributed training, set this count. Example: 2<br>    instance_count=1,<br>    # For training with p3dn instance use - ml.p3dn.24xlarge, with p4dn instance use - ml.p4d.24xlarge<br>    instance_type=&quot;ml.p4d.24xlarge&quot;,<br>    # instance_type=&quot;ml.g5.48xlarge&quot;,<br>    sagemaker_session=sagemaker_session,<br>    # Training using SMDataParallel Distributed Training Framework<br>    distribution={&quot;smdistributed&quot;: {&quot;dataparallel&quot;: {&quot;enabled&quot;: True}}},<br>    # Training with torchrun launcher, for instance types that do not support smddp<br>    # distribution={ &quot;torch_distributed&quot;: { &quot;enabled&quot;: True } },<br>    hyperparameters={&quot;region&quot;: sagemaker_session.boto_region_name},<br>    debugger_hook_config=False,<br>)<br>estimator.fit()</pre><h3>Training Phase</h3><p>A Training Job can be dynamically initiated and dispatched to a pre-specified high-performance compute instance, such as the <em>ml.p3.16xlarge</em>, equipped with 8 NVIDIA V100 GPUs. The SageMaker Distributed <strong>Data Parallelism</strong> (<a href="https://docs.aws.amazon.com/sagemaker/latest/dg/data-parallel-intro.html"><em>SMDDP</em></a>) library optimizes the underlying AWS infrastructure to support efficient collective communications and achieve near-linear scalability.</p><h3>Distributed Training Strategy</h3><p>When dealing with vast amounts of data and model architectures that are feasible on a single GPU, a data parallelism strategy is employed. Under this approach, data is evenly distributed across all GPUs, each loading the same model to perform training. Upon completion, the computational results are merged and parameters are updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRvc7UB6ngLV4aUE5d7Y5A.png" /><figcaption><a href="https://towardsdatascience.com/deep-learning-on-supercomputers-96319056c61f">source</a></figcaption></figure><h3>Massive Data Preprocessing and Management</h3><h3>Data Preprocessing</h3><p>Using PySpark RDD and Databricks, data stored in Databricks Tables is preprocessed in parallel to significantly reduce computation time. To manage the massive data volumes, preprocessing is designed to be batched; for instance, each batch processes one week’s data, with a total of 52 batches per year. The entire year’s data can be transformed in approximately two hours.</p><h3>Data Ingestion</h3><p>Processed data is uploaded to AWS S3 in batches, each consisting of hundreds of JSON files. These massive datasets are efficiently loaded using the HuggingFace Datasets API with a <strong><em>streaming </em></strong>method.</p><h3>Model Training</h3><h3>Rule Design for Data Allocation</h3><p>Based on the number of GPUs available, JSON files are strategically divided to optimize parallel processing. In an environment with 8 GPUs, the allocation is designed to distribute the workload evenly across all GPUs to maximize efficiency. For instance, if there are 8,000 JSON files, they are divided into 8 subsets, with each GPU processing one subset of 1,000 files each. This approach ensures balanced data processing and optimizes computational resources.</p><h3>Batch Training</h3><p>When designing <a href="https://github.com/aws/amazon-sagemaker-examples/blob/main/training/distributed_training/pytorch/data_parallel/mnist/code/train_pytorch_smdataparallel_mnist.py"><em>train.py</em></a>, different <a href="https://medium.com/@jonathan.tunguyen/distributed-machine-learning-training-8646a28c9095"><em>world_size</em></a> and <em>rank</em> parameters are set to adjust the distribution of training. These settings guide SageMaker on how to execute model training based on <a href="https://towardsdatascience.com/visual-intuition-on-ring-allreduce-for-distributed-deep-learning-d1f34b4911da"><strong><em>AllReduce</em></strong></a> (decentralized method) across various training environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*Z55hskHVYT8oQJrE.jpeg" /><figcaption>AllReduce: <a href="https://medium.com/towards-data-science/visual-intuition-on-ring-allreduce-for-distributed-deep-learning-d1f34b4911da">source</a></figcaption></figure><h3>Conclusion</h3><p>With AWS SageMaker and its distributed data parallel processing technology, we can effectively train large deep learning models, even in the face of billions of training samples. Through meticulously designed data preprocessing and robust resource management strategies, we not only enhance the efficiency of development and training but also ensure rapid processing of vast training samples in the era of large language models (LLM), which is crucial for improving model performance. Moreover, cloud computing infrastructure enables us to meet training objectives within a reasonable timeframe, maintaining competitiveness even as new generations of large models are frequently introduced to the market.</p><h3>Reference</h3><ul><li><a href="https://medium.com/@jonathan.tunguyen/distributed-machine-learning-training-8646a28c9095">Distributed Machine Learning Training (Part 1 — Data Parallelism)</a></li><li><a href="https://medium.com/ching-i/pytorch-%E5%88%86%E6%95%A3%E5%BC%8F%E8%A8%93%E7%B7%B4-distributeddataparallel-%E6%A6%82%E5%BF%B5%E7%AF%87-8378e0ead77">Pytorch 分散式訓練 DistributedDataParallel — 概念篇</a></li><li><a href="https://medium.com/ching-i/pytorch-%E5%88%86%E6%95%A3%E5%BC%8F%E8%A8%93%E7%B7%B4-distributeddataparallel-%E5%AF%A6%E4%BD%9C%E7%AF%87-35c762cb7e08">Pytorch 分散式訓練 DistributedDataParallel — 實作篇</a></li><li><a href="https://towardsdatascience.com/visual-intuition-on-ring-allreduce-for-distributed-deep-learning-d1f34b4911da">Visual intuition on ring-Allreduce for distributed Deep Learning</a></li><li>Github code: <a href="https://github.com/aws/amazon-sagemaker-examples/tree/main/training/distributed_training/pytorch/data_parallel/mnist">https://github.com/aws/amazon-sagemaker-examples/tree/main/training/distributed_training/pytorch/data_parallel/mnist</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0500d23368" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[客製化的大型語言模型 (LLM) — 針對特定領域做 Continual pre-training]]></title>
            <link>https://medium.com/@albertchen3389/%E5%AE%A2%E8%A3%BD%E5%8C%96%E7%9A%84%E5%A4%A7%E5%9E%8B%E8%AA%9E%E8%A8%80%E6%A8%A1%E5%9E%8B-llm-%E9%87%9D%E5%B0%8D%E7%89%B9%E5%AE%9A%E9%A0%98%E5%9F%9F%E5%81%9A-continual-pre-training-0a961a0161b9?source=rss-def57b3cef02------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a961a0161b9</guid>
            <category><![CDATA[pre-training]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Albert Chen]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 11:49:42 GMT</pubDate>
            <atom:updated>2024-01-29T13:36:35.236Z</atom:updated>
            <content:encoded><![CDATA[<h3>客製化的大型語言模型 (LLM) — 針對特定領域做 Continual pre-training</h3><p>一般的大型語言模型在特定領域，比如醫療或金融，往往無法滿足行業需求。因此，各行業急需客製化的LLM，可以利用行業累積的文本數據來訓練，這也是業界相對於學界的優勢。</p><h3>建立特定領域LLM的方法：</h3><ol><li>從零開始訓練: Building specialized LLMs entirely from domain-specific data. 有研究同時使用通用資料和領域資料混合，從頭開始訓練了一個大型語言模型，例如：金融領域的 <a href="https://medium.com/@albertchen3389/%E4%B8%8D%E5%90%8C%E6%96%BC%E4%BB%A5%E5%BE%80%E7%9A%84-pretraining-bloomberggpt-2fb77019f938">BloombergGPT</a>。</li><li>持續預訓練：在已有的LLM基礎上，用特定領域數據進行進一步的預訓練。 是一種在保持既有所學的同時 ，又能有效適應新領域的方法，也就是說在已有基礎能力的模型上加強模型在特定domain 的知識；一般而言使用 10B~100B tokens的資料來繼續做 pretraining。在 Continual pretraining 的過程中，最害怕的其實就是模型在學新知識的過程中把舊的知識接連忘掉，也就是所謂的 Forgetting 問題。</li><li>基礎大模型微調：在一個通用模型的基礎上做 instruction tuning（SFT)，這種做法的優點是可以快速看到不錯的結果，但要建立訓練資料集也要花費不少時間。</li><li>通用大型語言模型+向量知識庫：領域知識庫加上通用大型語言模型，針對通用大型語言模型見過的知識比較少的領域，利用向量資料庫等方式根據問題在領域知識庫中找到相關內容，再利用通用大模型強大的摘要和問答的能力產生回應。</li></ol><h3>持續預訓練的高效方法：</h3><p>第一種方式太耗費資源，不是一般企業負擔的起，本文先針對第二種方法做介紹。目前有研究針對法律領域發展了 <a href="https://github.com/pengxiao-song/LaWGPT">LawGPT</a>，也有針對財務領域發展的<a href="https://arxiv.org/abs/2311.08545">FinPythia-6.9B</a> ，其發展了domain-adaptive continual pre-training 的技術。<a href="https://arxiv.org/abs/2311.08545">FinPythia-6.9B</a> 的研究中提出了兩種策略：ETS-DACP 和 ETA-DACP，這兩種策略都涉及到根據<strong>任務資料的相似性</strong>和<strong>資訊新穎性</strong>來選擇最有資訊量的樣本。研究發現，基於這些策略精心選擇的預訓練資料，可以在大幅減少計算資源的情況下，達到更好的領域性能，是從頭構建領域特定模型的高效率替代方案。</p><p>以下是 <a href="https://arxiv.org/abs/2311.08545">FinPythia-6.9B</a> 之研究對比 未經 domain-adaptive continual pre-training 與 使用domain-adaptive continual pre-training 的問答結果，如下所示，其中 <strong>Pythia6.9B </strong>是未經 continual pre-training 的模型，由以下幾個問答結果，我們可以看出 <a href="https://arxiv.org/abs/2311.08545">FinPythia-6.9B</a> 的回答是比較貼近財金領域的。</p><blockquote><strong>Question: What is a SPAC?</strong></blockquote><blockquote><strong>Pythia6.9B:</strong> Spac is an acronym for Space. It is defined as either (1) above, just beneath, below, above, or through a port in the body of a planet, Moon, or other heavenly body; or (2) beyond a star’s sphere of influence, usually in interplanetary space or interstellar space; also, (3) outside the limits of the Milky Way Galaxy.</blockquote><blockquote><strong>FinPythia-6.9B:</strong> A SPAC is a type of merger and acquisition vehicle that is used to raise money from investors, use that money to identify a company that could be valuable to an interested party, then merge with the company and take it public. The use of the SPAC is to give investors a piece of the upside in the acquired company and allows the company to issue shares that may give investors a piece of the upside of the company as well.</blockquote><blockquote><strong>Question: Who is Cathie Wood?</strong></blockquote><blockquote><strong>Pythia-6.9B:</strong> Cathie Wood is the founder of All Things Organic, an organic marketing company that she founded in 2000. In addition to being an organic marketer, Cathie is also a Certified Coach, foodie, cook, a past lover of yoga, a certified teacher, mother and wife to three gorgeous children.</blockquote><blockquote><strong>FinPythia-6.9B:</strong> Cathie Wood is an American investor and advisor, the founder and chief executive officer of Ark Investment Management.</blockquote><blockquote><strong>Question: How do you like Fed’s latest policy to fight inflation?</strong></blockquote><blockquote><strong>Pythia6.9B: </strong>I like Fed’s latest policy to fight inflation, which was reported by Tyler. Fed’s latest policy was reported in a meeting on September 12 and it was named as SOMO, which stood for Standardized Open Market Operations. According to the policy, the U.S. central bank could buy $40 billion worth of financial instruments if the price of the instruments reach 6 percent.</blockquote><blockquote><strong>FinPythia-6.9B:</strong> There is a big confusion about Fed’s new policy to fight inflation. They are following a new policy from September 2022 called the fastest quarter-percentage point rate hikes in two decades to fight the ”costly” inflation which is the 8.5 percent rate of increase in food and energy prices that may aggravate inflation and lead to recession in the near future.</blockquote><blockquote><strong>Question: What is the difference between bond and stock in terms of risk profile?</strong></blockquote><blockquote><strong>Pythia-6.9B:</strong> Stock is less risky (you can liquidate your shares anytime) but bond is more risky (you can’t liquidate).</blockquote><blockquote><strong>FinPythia-6.9B: </strong>When you buy a bond, you receive a set of fixed payments from the issuer at a regular interval over a fixed term. You take on the full risk of the coupon payments not being made, so a bond is always considered to be a lower risk debt instrument than a stock. However, a stock is a more liquid investment than a bond. When buying a stock, you are buying shares in the company that the bond represents and you hold on to the stock until you want to cash out, and it can be used as collateral to borrow money.</blockquote><p><strong>Continual Pre-training</strong>耗費的運算資源如下：</p><p><a href="https://arxiv.org/abs/2311.08545">FinPythia-6.9B</a> 的 pre-training job 是執行在 AWS SageMaker上的 P4d.24xlarge instance。 由於模型大小不是特別的大，所以該研究只透過 <strong>DeepSpeed</strong> ZeRO Stage 2 (Rasley et al., 2020)，以使用 <strong>data parallelism</strong> 技術來加速模型訓練，並啓用了activation checkpointing 。花費了 <strong>18天</strong>來完成 pre-train ；而 FinPythia-1B 則花了 <strong>3 天</strong>的時間 pre-train 在 <strong>24 billion</strong> tokens。而 P4d.24xlarge 的規格如下表所示，有320G的 GPU記憶體。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*gHd1-gKFJYdTzLHOksIqQw.png" /></figure><h3>繁體中文LLM的持續預訓練</h3><p>而在發展<strong>繁中 LLM 時，通常需要始用繁中語料，對既有的 LLM 進行</strong>continual pre-training，因為目前國外大型企業發展的 LLM，例如 <a href="https://arxiv.org/abs/2307.09288">LLAMA 2</a>，使用的訓練語料裡，中文的佔比也只有<strong>0.13%，如下表，所以模型的繁體中文能力不是很好。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*_HXBGQYYa9dhdc6RlU6C4w.png" /></figure><p>針對<strong>繁體中文</strong>進行 continual pre-training 的研究中，有學者針對 <a href="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf">Llama-2–7b-chat</a> 做繁中化的版本 <a href="https://arxiv.org/abs/2401.03129"><em>Llama-2–7b-chat-cp</em></a><em>，</em> 然而，在繁體中文 LLM 的發展過程中，面臨的挑戰包括災難性遺忘和文本重複。文本重複的例子如下：針對問題：<strong><em>告訴我一些關於墨西哥城的事情</em></strong>。</p><p>模型的回答如下：</p><blockquote>墨西哥城（Mexico City）是墨西哥的首都，也是該國最大的城市 ，位於中美洲，距離墨西哥灣約 100公里，是一座<strong>歷史悠久的城 市</strong>，擁有<strong>豐富的文化</strong>資源。 墨西哥擁有<strong>豐富的歷史文化</strong>，是一座 <strong>歷史悠久的城市，擁有豐富的文化資源。墨西哥城擁有豐富的 歷史文化，是一座歷史悠久的城市，擁有豐富的文化資源</strong>。</blockquote><p>該研究提出的方法：</p><p>針對 <a href="https://huggingface.co/meta-llama/Llama-2-7b-chat-hf">Llama-2–7b-<strong>chat</strong></a>, 進行 <strong>pre-training</strong>，這個模型是由 7 billion 參數所組成，並且經過一系列的 alignment operations，包含 <strong>supervised fine-tuning (</strong>SFT) 和 RLHF，如 Figure 1 的右半與 Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0c3uobbRuX8hbUU-Mv-BQ.png" /><figcaption>Figure1, source: FINE-TUNING LLAMA 2: DOMAIN ADAPTATION OF A PRE-TRAINED MODEL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQKCOJDMtbxVl8YvSRoEUg.png" /><figcaption>Figure 2, source: <a href="https://www.leewayhertz.com/fine-tuning-llama2/">FINE-TUNING LLAMA 2: DOMAIN ADAPTATION OF A PRE-TRAINED MODEL</a></figcaption></figure><p>該研究的 pre-training process 使用了 <strong>1 billion tokens 的繁體中文語料</strong>，發展的模型稱為 <em>Llama-2–7b-chat-cp。</em>pre-training 使用的 global batch size 約是 4 million tokens. 過程中使用<strong> 64 V100 GPUs</strong>, 設定 gradient accumulation step 為 16。學習率在 continual pre-training 保持在 3e-5，且也針對 adapter approaches 實驗了額外的學習率 3e-4。</p><p>該研究並使用特定的 prompt 來比較繁中化的模型和原始的模型輸出結果。針對會發生的 forgetting 問題，該研究使用了以下幾個方法來克服。</p><ul><li>凍結層：凍結模型的某些層以保留先前學習的功能。凍結前十層、凍結最後的十層。</li><li>凍結模組：與凍結層類似，但專注於模型的特定部分模組，例如：FREEZE ATTN.: Freeze the self-attention modules in each layer of the model. ONLY ATTN.: Freeze all modules in each layer except the self-attention modules of the model. FREEZE MLP: Freeze the feed-forward modules in each model layer. ONLY MLP: Freeze all modules in each layer except the feed-forward modules of the model.</li><li>使用適配器：將可訓練組件納入模型架構中，以促進學習新訊息，同時保留舊知識。例如：LORA、 (IA) 3 (Liu et al., 2022): A technique involving element-wise multiplication of the model’s activations with a learned vector. We rescale the key and value matrices in self-attention modules and the inner activations in feed-forward modules in each model layer.</li></ul><h3>其它針對遺忘問題的研究</h3><p>也有研究為了防止模型遺忘了通用知識，而採用了不同的比例的專業知識語枓和通用知識語料之混合來進行模型訓練， ChatHome 這個LLM的研究，準備了豐富的家居裝修語料，包括專業文章、標準文件和網絡文件。接著，他們實施了基於家居裝修提示的指令調整策略。實驗結果表明，結合 continual 預訓練和模型微調可以顯著提升語言模型在特定領域的表現。在探索領域適應性預訓練（DAPT）的優勢時，發現當使用1:5的特定領域資料和通用領域資料比例時，模型展現了最佳的表現。</p><h3>結論</h3><p>我們探討了特定領域的語言模型持續預訓練（Continual Pre-training）的目的性和實作方法。透過比較從頭開始訓練和在已有通用模型基礎上進行持續預訓練的策略，我們發現後者不僅能有效適應新領域，還能減少所需的運算資源。本文也介紹了 FinPythia-6.9B等模型在財經領域的應用，並介紹如何利用領域適應性持續預訓練技術來提升特定領域內的問答表現。透過採用策略精選預訓練數據，這些模型在保持已有知識的同時，也展現出對新領域的高度適應性。</p><p>對於繁體中文的持續預訓練，面臨的挑戰包括災難性遺忘和文本重複問題。本文介紹了一系列策略和技術來克服這些問題，例如凍結模型層與模型模組、使用適配器等。這些方法為持續預訓練提供了新的視角，並對未來在不斷變化的領域內應用大型語言模型提供了參考。</p><p>總之，持續預訓練不僅為特定領域的客製化提供了一條有效的路徑，還為語言模型的可持續發展開闢了新的可能性，有助於在各個領域中實現更精確和個性化的應用。</p><h3>References:</h3><ul><li><a href="https://arxiv.org/abs/2307.09288">Llama 2: Open foundation and fine-tuned chat models.</a></li><li><a href="https://arxiv.org/abs/2307.15290">ChatHome: Development and evaluation of a domain-specific language model for home renovation.</a></li><li><a href="https://arxiv.org/abs/2311.08545">Efficient continual pre-training for building domain specific large language models.</a></li><li><a href="https://arxiv.org/abs/2401.03129">Examining forgetting in continual pre-training of aligned large language models.</a></li><li><a href="https://www.leewayhertz.com/fine-tuning-llama2/">Fine-tuning Llama 2: Domain adaptation of a pre-trained model.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a961a0161b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[大型語言模型的預訓練任務]]></title>
            <link>https://medium.com/@albertchen3389/%E5%A4%A7%E8%AA%9E%E8%A8%80%E6%A8%A1%E5%9E%8B%E7%9A%84%E9%A0%90%E8%A8%93%E7%B7%B4%E4%BB%BB%E5%8B%99-b831dcf8f6f7?source=rss-def57b3cef02------2</link>
            <guid isPermaLink="false">https://medium.com/p/b831dcf8f6f7</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[pre-trained-model]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Albert Chen]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 09:45:34 GMT</pubDate>
            <atom:updated>2024-11-05T05:24:56.991Z</atom:updated>
            <content:encoded><![CDATA[<p>ChatGPT 爆紅之後，大家都在聊 LLM，通常大家都會學到 GPT 這類 LLM 在預訓練階段是在訓練模型具備文字接龍的能力，但其實還有很多種預訓練任務。本文首先先談目前最火熱的 GPT 的預訓練任務，再來談談之前也曾帶來熱潮的BERT所使用的預訓練任務，最後是幾個其它也很常見的預訓練任務。</p><h4>因果語言建模 (Causal Language Modeling, CLM),如：GPT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*UyhIOB08DdzT1ZUkOhbkUA.png" /><figcaption>source: <a href="https://learn.deeplearning.ai/chatgpt-building-system/lesson/2/language-models,-the-chat-format-and-tokens">DeepLearning.AI: Building Systems with the ChatGPT API</a></figcaption></figure><p>在 CLM 中，模型經過訓練，可以在給定先前的 tokens 的情況下預測序列中的下一個 token，如上圖。</p><p>在訓練期間，把 Input tokens 輸入到模型中，例如： My favorite food is a , 而模型預測下一個 token 的機率分佈，例如下圖，而評估模型學習成效的 loss，則是根據模型的預測 token 和實際 target token 計算誤差值，其中的實際 target token 就只是移動到下一個位置的 Input token，這就是一種自監督學習，可以僅由輸入取得模型的學習目標 (label)。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgbnQxoED-jUqlNiX4Vnlg.png" /><figcaption>source: Demystifying LLM Parameters for Inference</figcaption></figure><p>上圖中 temperature sampling 的靈感來自統計熱力學，其中高溫意味著較低能量狀態更有可能被遇到。在機率模型中，logit扮演著能量的角色，我們可以通過在將logit輸入softmax之前除以溫度來實現 temperature sampling，從而獲得抽樣的機率分布。以下程式參考自文章： <a href="https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277">How to sample from language models</a>。</p><pre>&gt;&gt;&gt; import torch&gt;&gt;&gt; import torch.nn.functional as F<br>&gt;&gt;&gt; a = torch.tensor([1,2,3,4.])<br>&gt;&gt;&gt; F.softmax(a, dim=0)tensor([0.0321, 0.0871, 0.2369, 0.6439])<br>&gt;&gt;&gt; F.softmax(a/.5, dim=0)tensor([0.0021, 0.0158, 0.1171, 0.8650])<br>&gt;&gt;&gt; F.softmax(a/1.5, dim=0)tensor([0.0708, 0.1378, 0.2685, 0.5229])<br>&gt;&gt;&gt; F.softmax(a/1e-6, dim=0)tensor([0., 0., 0., 1.])</pre><p>較低的溫度設定會讓模型對其機率高的選擇更有信心，而高於1的溫度則會降低信心，如下圖。0溫度相當於argmax/最大似然，而無限溫度則對應於均勻分布的抽樣。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*N8DYUq44Kkq7FZmcgliS2g.png" /><figcaption>source: Demystifying LLM Parameters for Inference</figcaption></figure><p>模型架構：CLM 通常與 GPT 等自回歸模型一起使用。這些模型使用 <strong>單向</strong>（從左到右）的 Transformer 架構，其中每個 token 只能處理其前面的 token。這可以防止模型在訓練期間透過專注於目標 token 來「作弊」。<br>輸出模型：經過微調的 CLM 模型可以透過一次預測一個 token 來產生連貫的文本，使其適合 <strong>文本生成任務</strong>。然而，與 Mask Language Modeling (MLM) 相比，它在捕捉雙向上下文方面可能不那麼有效。</p><h3>BERT</h3><p>BERT是幾年前很火熱的語言模型，其也是採用「無監督預訓練 + 監督微調」的方法，與 GPT-1 相同；但是，BERT是採用雙向語言模型，且BERT 的預訓練任務與 GPT-1 不同，如下兩個：<strong>Masked Language Modeling (MLM）</strong>和 <strong>Next Sentence Prediction（NSP</strong>）。</p><p><strong>MLM 預訓練任務:</strong><br>BERT 具體採用的方法是，隨機選擇 15% 的 tokens 出來，但並非把它們全部都 MASK 掉，而是：</p><ul><li>其中的 <strong>80%</strong> 被替換為 [MASK]，類似 my dog is hairy -&gt; my dog is [MASK]。</li><li>其中的 10% 被替換為一個隨機 token，類似 my dog is hairy -&gt; my dog is apple。</li><li>剩餘的 10% 不變。<br>至於 80–10–10 是怎麼定出來的，Google 團隊也是由下圖的幾種數字組合試出來的。那為什麼不是 100% 替換為 [MASK]? 假設我們在進行情感分析，預訓練時的目標是讓模型學習如何從句子的上下文推斷出一個被遮罩掉的詞，比如「my dog is [MASK]」。如果我們總是用 [MASK]，那麼在預訓練過程中，模型只會專注於學會如何填補這些被遮罩的詞，並且過於依賴 [MASK] 這個標記。當它在測試階段遇到像「my dog is happy」這樣的正常句子時，因為沒有 [MASK]，模型可能會「不知所措」，因為它總是在預訓練過程中依賴這個特殊標記。<strong>但是，當引入 10% 的隨機替換和 10% 的未改變 token 時</strong>，模型必須學會在各種情況下（包括正常的未被遮罩的 token 和隨機的 token）依然保持良好的上下文理解能力，這使得模型能夠更好地應對真實世界中的任務。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Rdrb_smGH7sHg-n.png" /><figcaption>source: BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</figcaption></figure><ul><li>MNLI 任務：Multi-Genre Natural Language Inference 是一個大規模的蘊含（entailment）分類任務（Williams et al., 2018）。給定一對句子，預測第二個句子相對於第一個句子是蘊含、矛盾還是中性。這種任務幫助模型學習如何理解和分析文本中的複雜語言關係，特別是在不同類型和風格的文本中。MNLI涵蓋了廣泛的文本類型，包括新聞報導、小說、科學文章等，從而使其成為衡量語言模型理解多樣化語言內容的一個重要工具。</li><li>NER 任務：Named Entity Recognition 命名實體辨識任務，如下圖的文本中標示了幾個命名實體。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O4efJrZPe516gISN.jpg" /><figcaption>source: <a href="https://www.amygb.ai/blog/what-is-named-entity-recognition-in-nlp">What is Named Entity Recognition in Natural Language Processing?</a></figcaption></figure><ul><li>典型使用MLM 的模型包括BERT和SpanBERT。</li></ul><p><strong>NSP 預訓練任務</strong><br>許多 NLP 任務（例如<strong>問答、推理</strong>等等）都涉及句子之間關係的理解，這在一般性的語言建模過程中是學習不到的。因此 Google 想用預訓練階段的 NSP 任務來解決這個痛點。 NSP 預訓練任務所準備的數據，是從單一語種的語料庫中取出兩個句子 Si 和 Sj，並檢查這些句子的順序是否正確。其中50% 的情況下B 就是實際跟在A 後面的句子，50% 的情況下B 是隨機取的。這樣語言模型就是在面對一個二元分類問題進行預訓練，例如：</p><pre>INPUT: [CLS] the man went to [MASK] store [SEP]<br>       he bought a gallon [MASK] milk [SEP]<br>LABEL: IsNext</pre><p>BERT 需要理解這個句子，並猜測出缺失的詞可能是 “the”（因為 “the store” 是一個常見的詞組）。上面的例子中，兩個句子之間的關係被標記為 “IsNext”。這意味著這兩個句子在邏輯上是連貫的。BERT 需要學習如何判斷兩個句子是否有邏輯上的連續性。</p><p>透過這樣的訓練，BERT 不僅學會了詞語之間的關係，還學會了如何理解句子之間的相關性，並捕捉句子級別的表示(representation)這對於後續的各種語言處理任務非常有幫助。</p><pre>INPUT: [CLS] the man [MASK] to the store [SEP]<br>       penguin [MASK] are flight ##less birds [SEP]<br>LABEL: NotNext</pre><p>上面的兩個例子中，CLS 是一個表示「classification」的 token，SEP 是一個表示「separate」的 token。這2種預訓練任務，讓 BERT 不只學到到字維度的語言知識，也讓 BERT 學到句子維度的語言結構。</p><h3>其它常見的預訓練任務</h3><p>常見的預訓練任務除了GPT 這類因果語言建模使用的 Next Token Prediction； BERT 使用的 Mask Language Modeling（MLM)，Next Sentence Prediction (NSP) 之外，還有Denoising AutoEncoder（DAE）、Replaced Token Detection（RTD）和 Sentence Order Prediction（SOP）。</p><ul><li><strong>去噪自編碼器（DAE）</strong>：DAE用於向原始語料庫添加噪聲，並使用包含噪聲的語料庫重建原始輸入。BART 是一個代表性的例子。DAE通常會對整個句子進行更全面的修改，不僅僅是遮蔽或替換個別單詞。例如，它可能會對句子的結構進行改動，或者在句子中加入錯誤信息。這樣做的目的是讓模型學習在更複雜的情況下恢復原始文本。舉例來說，原句子 “小狗在公園玩耍” 可能會被改為 “在小公園狗玩耍”，模型的任務就是要從這個扭曲的句子中恢復原始的順序和意義。BART 是由 seq2seq 模型建構的降噪自動編碼器，採用的是編碼器-解碼器模型架構。預訓練任務主要包括使用噪聲破壞文本，並使用seq2seq模型重建原始文本。編碼層採用雙向Transformer。它使用五種添加 noise 的方法：（1）單字遮蔽；（2）字刪除；(3)跨度遮蔽；（4）句子改編；（5）文件重新排列。</li><li><strong>替換Token檢測（RTD）</strong>：RTD是一項判斷語言模型是否替換了當前Token的判別任務。這項任務在ELECTRA 中使用。透過訓練模型區分Token是否被替換，模型可以獲取語言知識。</li></ul><p>假設有一個原始句子：</p><blockquote>“The <strong>cat</strong> sat on the mat.”</blockquote><p>然後，我們隨機替換其中的一個詞，比如將 “cat” 替換為 “apple”：</p><blockquote>“The <strong>apple</strong> sat on the mat.”</blockquote><p>在 RTD 任務中，模型的目標是識別出哪個詞是被替換的。在這個例子中，模型需要識別出 “apple” 這個詞是不適當的，因為一般來說，蘋果不會“坐”在墊子上，而貓會。</p><ul><li><strong>句子順序預測（SOP）</strong>：與NSP不同，SOP使用來自一篇文檔的兩個相鄰片段作為正面樣本，並將這兩個片段的交換順序作為負面樣本。這樣，預訓練模型（PFMs）可以更好地模擬句子之間的相關性，例如ALBERT。SOP使用一篇文檔中的兩個相鄰片段作為正面樣本，然後將這些片段的順序顛倒作為負面樣本。舉例來說，假設有兩個句子：“我去超市購物。”接著是，“我買了一些水果。”在SOP中，這個順序是正確的（正面樣本）。但如果順序是：“我買了一些水果。”接著是，“我去超市購物。”這就是不正確的順序（負面樣本）。這種方法幫助語言模型像ALBERT這樣更好地理解文本中句子間的關聯性和順序。</li></ul><p>綜上，RTD、NSP和SOP都是採用<strong>對比學習方法</strong>，而這些方法假設觀察到的樣本在語義上比隨機樣本更相似。</p><p>本文總結了大型語言模型（LLM）中各種預訓練任務的重要性和多樣性。從GPT的因果語言建模（CLM）到BERT的MLM和NSP，每種任務對於提升模型對語言環境和結構的理解都有其重要性。至於其他的任務，如：DAE、替RTD 和SOP，進一步的豐富了預訓練的範疇，使LLM在語言理解和生成方面的能力更加全面。這些多樣的預訓練方法凸顯了LLM在AI語言領域的迅速發展和多功能性。</p><p>Reference:</p><ul><li><a href="https://medium.com/@tom_21755/understanding-causal-llms-masked-llm-s-and-seq2seq-a-guide-to-language-model-training-d4457bbd07fa">Understanding Causal LLM’s, Masked LLM’s, and Seq2Seq: A Guide to Language Model Training Approaches</a></li><li><a href="https://arxiv.org/abs/2307.06435">A Comprehensive Overview of Large Language Models</a></li><li><a href="https://arxiv.org/abs/1810.04805">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a></li><li><a href="https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277">How to sample from language models</a></li><li><a href="https://medium.com/@jpraveenkanna/demystifying-llm-configurations-for-inference-3866979806de">Demystifying LLM Parameters for Inference</a></li><li><a href="https://www.mikecaptain.com/2023/03/06/captain-aigc-2-llm/#72bert-%E7%9A%84%E8%AE%AD%E7%BB%83%E6%96%B9%E6%B3%95">人工智能 LLM 革命破晓：一文读懂当下超大语言模型发展现状</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b831dcf8f6f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[不同於以往的 pretraining — BloombergGPT]]></title>
            <link>https://medium.com/@albertchen3389/%E4%B8%8D%E5%90%8C%E6%96%BC%E4%BB%A5%E5%BE%80%E7%9A%84-pretraining-bloomberggpt-2fb77019f938?source=rss-def57b3cef02------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fb77019f938</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[pretrained-model]]></category>
            <dc:creator><![CDATA[Albert Chen]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 07:51:27 GMT</pubDate>
            <atom:updated>2024-01-21T13:27:32.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EjRkxK_CN0wZJDPK" /><figcaption>source: <br>Sebastian Raschka, PhD, <a href="https://www.linkedin.com/posts/sebastianraschka_llm-ai-deeplearning-activity-7144313448443576320-KfmO?utm_source=share&amp;utm_medium=member_desktop">https://www.linkedin.com/posts/sebastianraschka_llm-ai-deeplearning-activity-7144313448443576320-KfmO?utm_source=share&amp;utm_medium=member_desktop</a></figcaption></figure><p>重點摘錄如下：</p><ol><li>混合語料庫預訓練方法：BloombergGPT 在預訓練階段同時使用了通用域和金融特定域的語料庫。例如，它可能同時學習了來自新聞網站的一般文章（如政治、文化等）和專門的金融報告或市場分析。這種混合使模型既瞭解一般語言，又對金融術語和概念有深刻理解。用於預訓練 BloombergGPT 的特定域語料庫主要來自 <a href="https://www.bloomberg.com/professional/solution/bloomberg-terminal/">Bloomberg Terminal</a>，而這是一個廣泛使用的金融數據和分析平台，其數據包括金融新聞、市場報告、和經濟分析等，是金融專業人士常使用的資源。訓練資料的 Data Mixture 比例如下表：</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*voPEgtYmmViganWTKRpLLg.png" /></figure><ol><li>與傳統方法的不同：傳統的大型語言模型（如GPT-3）首先只使用通用語料庫進行預訓練，然後在特定的應用領域進行微調。而BloombergGPT 從一開始就融合了這兩種語料，目的是直接訓練模型對金融領域的深入理解。</li><li>優點：這種方法使BloombergGPT 在理解金融市場、分析金融報告或預測市場趨勢方面更加專業和精確。它更好地捕捉了金融領域的特殊術語和概念。</li><li>缺點：這可能會讓模型在非金融領域的表現受到限制。然而，根據論文的結果，這種影響似乎不顯著，因為BloombergGPT 在通用語言任務上仍然表現良好。</li></ol><p>有研究者去試各種不同LLM 的訓練方法是件好事，讓我們可以基於前人的研究來加快自己的研發！</p><p>Reference:<br>- BloombergGPT: A Large Language Model for Finance, <a href="https://arxiv.org/pdf/2303.17564.pdf">https://arxiv.org/pdf/2303.17564.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fb77019f938" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM 時代下的繁體中文 Tokenization?]]></title>
            <link>https://medium.com/@albertchen3389/llm-%E6%99%82%E4%BB%A3%E4%B8%8B%E7%9A%84%E7%B9%81%E9%AB%94%E4%B8%AD%E6%96%87-tokenization-d91409a55bce?source=rss-def57b3cef02------2</link>
            <guid isPermaLink="false">https://medium.com/p/d91409a55bce</guid>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Albert Chen]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 08:52:15 GMT</pubDate>
            <atom:updated>2023-12-25T11:09:04.773Z</atom:updated>
            <content:encoded><![CDATA[<p>在預訓練語言模型（PLMs）中，斷詞是基礎性的工作。現有的中文PLMs分詞方法通常將每個字元(char)視為不可分割的標記。然而，它們忽略了中文書寫系統的獨特特徵，即在字元級別以下存在額外的語言信息，也就是子字元級別。為了利用這些信息，在簡體中文的研究中，已有學者提出了子字元（簡稱SubChar）斷詞方法。具體而言，他們首先通過根據字元的字形或發音將每個中文字元轉換為簡短的序列來編碼輸入文本，然後基於編碼後的文本進行子詞分割來構建詞彙表。實驗結果展示出，SubChar斷詞方法相對於現有的斷詞方法具有兩個主要優勢：1）它們可以將輸入斷詞為更短的序列，從而提高了計算效率。2）基於發音的SubChar斷詞器可以將中文同音詞編碼成相同的拼音序列並產生相同的斷詞輸出，因此對同音字的錯誤拼寫具有強健性。該研究的代碼在：<a href="https://github.com/thunlp/SubCharTokenization">https://github.com/thunlp/SubCharTokenization</a>, Hugginface上也有該研究的 tokenization 模型檔可供大家使用：<a href="https://huggingface.co/thunlp/SubCharTokenization/tree/main">https://huggingface.co/thunlp/SubCharTokenization/tree/main</a></p><p>他們的 tokenization 範例如下圖，而 Wubi, Pinyin 是2種中文輸入法。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WvgL7ABxVmOTBc_L" /><figcaption>source: <a href="https://direct.mit.edu/tacl/article/doi/10.1162/tacl_a_00560/116047/Sub-Character-Tokenization-for-Chinese-Pretrained">Sub-Character Tokenization for Chinese Pretrained Language Models</a></figcaption></figure><p>其中Wubi輸入法的例子如下圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-rLhC_dNDN8p2z0f.jpg" /><figcaption>source: <a href="https://www.sciencedirect.com/science/article/pii/S1319157823002082#f0005">GWBNER: A named entity recognition method based on character glyph and word boundary features for Chinese EHRs</a></figcaption></figure><p>什麼是 Tokenization?</p><p>基本上就是把句子拆解為以 token 為單位的符號，並將其轉換為 token_id, 如下圖的概念。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*UkJnAxQcKKRgchJDTzzVaA.png" /><figcaption>source: <a href="https://learn.deeplearning.ai/finetuning-large-language-models/">https://learn.deeplearning.ai/finetuning-large-language-models/</a></figcaption></figure><p>最近測試了繁中的LLM, <a href="https://huggingface.co/yentinglin/Taiwan-LLM-7B-v2.1-chat">yentinglin/Taiwan-LLM-7B-v2.1-chat</a>, 對繁體中文的文本切 token, 發現其tokenization 演算法似乎還是沿用Llama 的 Byte Pair Encoding (BPE)方法。</p><p>測試的中文輸入句子：我愛台灣人工智慧學校</p><p>tokenization 結果為：[’▁’, ‘我’, ‘愛’, ‘台’, ‘&lt;0xE7&gt;’, ‘&lt;0x81&gt;’, ‘&lt;0xA3&gt;’, ‘人’, ‘工’, ‘智’, ‘&lt;0xE6&gt;’, ‘&lt;0x85&gt;’, ‘&lt;0xA7&gt;’, ‘學’, ‘校’]</p><p>程式碼的執行畫面如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5g4Ij1GmcW4P9zRR3jctGA.png" /></figure><p>目前一般個人或小型企業，基於運算能力與資料集的不足，大多只能對 base model 進行 fine-tuning, 而 fine-tuning 只能使用和 base model 一樣的 tokenization 方法。如果要使用針對繁體中文特製的tokenization 方法，就必須要對 base model 進行 Continual Pre-training, 也就是使用新的tokens和更新後的詞彙表對模型進行預訓練。舉例如下：</p><pre>&quot;台北市長參加了開幕典禮。&quot;<br>例如針對繁體中文發展的 tokenization 可能是將句子分成了：<br><br><br>[&quot;台北市&quot;, &quot;長&quot;, &quot;參加&quot;, &quot;了&quot;, &quot;開幕式&quot;, &quot;。&quot;]<br><br>而原來的BPE模型可能會將其分割成：<br><br>[&quot;台&quot;, &quot;北&quot;, &quot;市&quot;, &quot;長&quot;, &quot;參&quot;, &quot;加&quot;, &quot;了&quot;, &quot;開&quot;, &quot;幕&quot;, &quot;式&quot;, &quot;。&quot;]</pre><p>在 Continual Pre-training過程中，模型透過學習新的tokens（如”台北市”）和它們在語境中的使用，調整其內部的權重和表示，以更好地理解和預測繁體中文文本。</p><p>透過這個過程，模型最終能夠處理和理解使用新tokenization規則的繁體中文文本，即使這種規則與原始預訓練時的規則不同。這樣的Continual Pre-training可以讓模型更適應新的語言環境和任務。</p><p>台灣的 <a href="https://github.com/MiuLab/Taiwan-LLM">Taiwan-LLM</a>，在其研究中，是有進行 Continual Pre-training 的階段的，在這個階段，該研究團隊由一個基礎語言模型開始，例如Llama2，並在一個大規模的台灣語料庫上進一步進行預訓練。目標是最大化模型在台灣語料庫上的對數似然，以適應台灣繁體中文的使用。這一過程中涉及了高品質文字的篩選，以確保數據質量，並排除垃圾和有害內容。然而，在他們的研究中，似乎沒有針對繁體中文的 tokenization 提出特別的方法，因此可能無法完全捕捉繁體中文的特殊性。</p><p>在目前這個LLM時代下，針對繁體中文的大型語言模型似乎還沒有發展出適合的tokenization方法，並使用特製的繁體中文tokenization語料來訓練模型。我們需要思考針對繁中大型語言模型發展適合的tokenization方法的目標是什麼，這是一個值得學界和產業界共同探索的問題。期待未來有更多針對繁體中文特性的研究和開發，以提高模型在理解和生成繁體中文文本方面的準確性和效率。</p><p>Reference</p><ul><li><a href="https://direct.mit.edu/tacl/article/doi/10.1162/tacl_a_00560/116047/Sub-Character-Tokenization-for-Chinese-Pretrained">Sub-Character Tokenization for Chinese Pretrained Language Models</a></li><li><a href="https://www.sciencedirect.com/science/article/pii/S1319157823002082#f0005">GWBNER: A named entity recognition method based on character glyph and word boundary features for Chinese EHRs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d91409a55bce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>