<?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 Guan on Medium]]></title>
        <description><![CDATA[Stories by Guan on Medium]]></description>
        <link>https://medium.com/@laborintelligent?source=rss-e547cb7eedb0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*V6Nxmc0pXuRqiWAlAYq3Ng.jpeg</url>
            <title>Stories by Guan on Medium</title>
            <link>https://medium.com/@laborintelligent?source=rss-e547cb7eedb0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:34:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@laborintelligent/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[寫在入職 SoC 架構團隊三個月後]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/%E5%AF%AB%E5%9C%A8%E5%85%A5%E8%81%B7%E4%B8%89%E5%80%8B%E6%9C%88%E5%BE%8C-2816c9eca3b9?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2816c9eca3b9</guid>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 06:40:47 GMT</pubDate>
            <atom:updated>2025-01-26T03:57:52.113Z</atom:updated>
            <content:encoded><![CDATA[<p>其實超過三個月了，只是三個月在部門內有其意義且又恰好逢 2024 年末。</p><p>我的背景很普通，求學經歷普通、職業生涯普通，甚至說有點古怪，可以看一下前篇「我的 Linux Kernel 學習之路」了解，我認為做為一名普通工程師的分享是這篇文章的價值之一。</p><p>目前我在 MTK 負責 SoC 架構分析的團隊：同 BG 的其他部門負責 CPU、GPU、NPU 的設計，我所在部門就傾向 SoC 當中的 Bus 和 Memory system；但我們並不直接設計硬體，而是透過系統行為的分析和 High Level Synthesis (HLS) 的方式參與 SoC 架構，舉例來說，現代很多工作都需要多個 xPU，如相機應用需要 CPU + ISP + GPU，就算這三個單獨的設計都是巧奪天工，但之間的 Bus 和 Memory system 如果無法使它們有良好的串行合作，最終也只會是 memory-bound，像是「木桶理論」一樣。</p><p>由於系統的行為過於複雜，現代 SoC 有多個 master 和多個層級的 cache 以及 DRAM，是盤根錯節的拓樸結構，和最初像是馮紐曼架構的 CPU-DRAM 行為已經有很大的差異，已經不能接受僅以 master 的角度看待 SoC 了；此外，軟硬體行為的交錯讓整件事情更糟糕，不論是 OS 和內部 User 的軟體設計都需要有系統級的角度才能夠使場景效能符合預期，譬如如何善用硬體資源以減少 MCPS 以及功耗；所以透過設計模型和模擬分析去解釋系統行為、了解系統限制、 解決軟硬體 Bug 和效能優化就是我所在部門的主要工作內容了。</p><p>剛剛談到的僅僅是 Performace，實務上 Power 通常也是關注重點，兩者之合就是 Power Efficiency 能效。</p><p>Power 除了表面上的瓦數外，最近接觸到我們也會參與 Power 的硬體設計如 Power Management IC (PMIC) ，譬如現在知道了原來 cycle 是透過石英振盪器產生，再轉換成各個 IP 所需要的頻率，其中可以透過軟體去改變 register 達到調頻的目的，這又進一步拓展了我的知識領域，算是一個很細節的意外收穫。</p><p>能效和續航力強烈相關影響使用者體驗外，如果在特定場景能效不佳導致 SoC 必須使用比較大的功耗才能運作，有可能會引入另一複雜的因素：溫度；溫度提升最直觀影響的是 SoC 當中所有 DRAM 的效能，譬如高溫會導致 DRAM flush 更頻繁，整機能效會劇烈下滑；再來，如果置之不理輕則系統崩潰，重則起火或爆炸，故 thermal 相關的議題也很重要。</p><p>最後，有兩件部門讓我相當驚艷的傳統/文化/風氣，一個是資深同事在費米估計 (<a href="https://zh.wikipedia.org/wiki/Guesstimate">Guesstimate</a>) 上的功力，第二個是化繁為簡。</p><p>前者是因為很多計畫前期因為引入新 IP 導致沒有可以參照的數據，譬如引入某種 <a href="https://developer.arm.com/documentation/den0013/d/Multi-core-processors/Cache-coherency">cache coherency</a> 機制導致cache行為/Latency 的改變，進而影響Performace/Power，又並非所有 IP 都能夠即時有 HLS 的數據參考，但長官/合作部門還是需要有一個估計值以評估 pro and con，此時就需要「抓手感」；基於過去對於硬體設計/OS/APP的經驗，透過給出多個評估數字計算最終的行為變化，譬如：CPU latency +20ns/DRAM traffic -200MBps/GPU exe. time -3% → -100mW on ??? scene。</p><p>第二個是由於部門性質，需要常常回答最上級長官「單純但複雜」的問題，像是「如果在 ??? 場景 L3 cache +2MB/4MB/6MB，會帶來多少好處？」，這樣看似「大哉問」的問題卻會對研發部門的投資方向有深遠影響；此時需要把複雜的問題簡化、去蕪存菁，在一頁投影片中就能直擊問題的核心，甚至用一句話就能夠概括一頁投影片，讓理解資訊的成本最小化、獲得的資訊最大化，又是另一個部門的重要課題。</p><p>Anyways，短短三個月卻又大幅拓展了我對電腦科學的知識領域以及未來想像，期待未來有機會接觸一些資深同事的 HLS 業務，讓技能樹再更向外擴張。</p><p>這三年來重回 CS 最底層的收穫是不可思議地，對整個知識體系的理解又再更向上一步，過一段時間再回來思考最先進的那些深度學習的運算任務和原理應該也能夠有更深層次的理解吧。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*hAtd16yZ2iYcbDi7.gif" /><figcaption>“Flesh is weak, but steel endures.” 最近愛上戰錘40K，越來越有這個感覺</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2816c9eca3b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/%E5%AF%AB%E5%9C%A8%E5%85%A5%E8%81%B7%E4%B8%89%E5%80%8B%E6%9C%88%E5%BE%8C-2816c9eca3b9">寫在入職 SoC 架構團隊三個月後</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[我的 Linux Kerenl 學習路程]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/%E6%88%91%E7%9A%84-linux-kerenl-%E5%AD%B8%E7%BF%92%E8%B7%AF%E7%A8%8B-7d507440f473?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d507440f473</guid>
            <category><![CDATA[作業系統]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 10:05:20 GMT</pubDate>
            <atom:updated>2025-07-28T15:14:59.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>我的 Linux Kernel 學習之路</h3><h4>也算是半個文組翻身吧</h4><p>你可以先看看我的課程筆記 <a href="https://hackmd.io/@Kuanch/linux2024-overview">Linux Kernel Internals 2024 Spring Collections</a>，如果覺得符合期待再往下閱讀。</p><h3>背景</h3><p>我的背景是統計系畢業，實習時接觸了 Computer Vision，當時是 2018 年左右，也幾乎是那個時候才有比較高強度的 Python 的練習；由於我不是本科系，對於 C/C++ 幾乎是僅勉強能讀懂，或是需要花時間慢慢查閱範例和文檔才能夠撰寫能夠運作的 C/C++ 程式等。</p><p>我記得在我的第二份正職工作，為了要防止模型被客戶取出，特意寫了一隻用 SHA256 把開機時從 Gitlab 下載的 Public Key 解出 root 密碼的 C++ 程式，那是我僅有能夠記起的 C/C++ 經驗，由於我的兩份正職工作都和 DL 強烈相關，故大多數時間還是寫 Python，一些協助後端開發的經驗也是以 Python 為主，可以說 2022 年以前， Python 是我用於接觸 CS 相關知識的母語，雖然也陸續搞過 C# 和 Go，但反正跟 C/C++ 不熟。</p><h3><strong>回成大唸碩</strong></h3><p>回到成大讀碩後也不是本科系，是運算學院的人工智慧機器人學位學程，碩論也是延續我第二份正職遺留的問題，使用 DL 解決點雲分割問題。</p><p>But, 回到成大後有意識的開始往更底層的 CS 知識走；首先是靠數位 IC 設計理解了 verilog 和電路設計的相關知識，再來是 jserv 開的計算機結構，最後是 jserv 開的 Linux Kernel。</p><p>我還記得在計結的第一份作業，應該是 RISCV 搭配 Ripes 分析一隻簡單的 C 程式；突然就理解到透過電位高低形成的二進制和 32 個 ports 就可以產生任意的 asm 指令，然後就可以驅動 CPU pipeline。</p><p>大概就是那一刻我對於現代計算機是如何運作的有一份初步的認識，也對我後來 Linux Kernel 的學習理解有很大的幫助，所以如果要我推薦這個方向修課的最小組合，就會是 Digital IC Design 相關 + 計組計結相關 + OS 相關。</p><p>其中計組一定要上強度，因為它負責將最底層的 IC 和上層的 OS 連結，學得好對於後來 OS 的學習會事半功倍。</p><h3>「神課」Linux Kernel</h3><p>碩二下的時候我才選到傳說中成大電資必定要修的這門神課，第一個的建議是越早修越好，越早修後續在其他相關課程的成長幅度越大；第二個建議是由於這門課的課程設計，你砸的時間和你的收穫高度相關，所以記得盡量把時間空出來，花越多時間你越強（這件事是難能可貴的，相信看過很多爛課的你深有體會）。</p><p><strong>選擇你的「主修」Subsystem</strong></p><p>從歷年課程的 <a href="https://hackmd.io/@sysprog/linux2024-projects">Term Project</a> 中，會發現每年一定會有的是 CPU 相關，我認為這是因為比起記憶體和檔案系統，它是相對好上手的 subsystem，你可以參考 <a href="https://makelinux.github.io/kernel/map/">Linux Kernel map</a>，並選擇你的「主修」；所謂主修是如 “I/O”, “CPU”, “memory”, “storage”, “network” 等 subsystem，並從其中重要的部件起手，如 CPU 中最重要的函式是如 schedule(), context_switch(), pick_next_task() 等，最重要的結構是 task_struct 和 sched_entity 等，越有邏輯流程的部件就越適合看 code 起手，像上述提到的部件都是在 CPU 當中的 Scheduler。</p><p>從 Linux Kernel map 當中你也可以觀察到，相鄰的 subsystem 有強烈相關，像是討論 CPU 不可能不討論 I/O 和 memory 帶來的影響。選擇一個主修的 subsystem 只是方便你有個開始，最終你還是要逐個熟悉每一個 subsystem 的。</p><p>題外話，不嚴謹地說，每一個「主修」似乎恰好對應一線廠的業務，如聯發科以 CPU 為主、瑞昱以 I/O 為主、群聯和SMI以 storage 為主，當然不是那麼絕對，像群聯SMI擅長的 PCIE 介面就屬於 I/O，瑞昱的網通事業群也與 network 強烈相關，只是一個就業的參考 （也可能是我以管窺豹了）。</p><p><strong><em>2024/12/29 更正：</em></strong><br>聯發科開發的是 SoC，故 CPU/GPU/NPU/ISP/Modem/AP/MemSYS/Interconnect 都是開發內容，其餘 IP 則多少都會使用 ARM 公版；故並沒有什麼「聯發科以 CPU 為主」這件事情，我想其他一線廠應該也是類似狀況，上段文字寫在入職之前理解有誤，請見諒。</p><p><strong>不要「舉燭」</strong></p><p>這一點也被 jserv 強調許多次，這是因為很多同學（包括我）寫筆記寫到走火入魔，很多時候看不懂為什麼是這樣實作的，就開始幻想，有些時候甚至連實作都沒看就開始幻想，這是不對的。</p><p>首先，直接讀程式碼是必要的，再來是讀 Patch，有些程式碼是被改了又改、改了又改的，不讀 Patch 了解前因後果有時候根本不可能看懂。</p><p>最後，做實驗眼見為憑；把 qemu 和相關 toolchain 搞定，直接用 gdb 追蹤是最笨最沒有效率但也最具體的方法，對初學者有巨大幫助。</p><p>然而上述也不一定完全有效，據現役發哥 CAI E8 工程師（我弟），有時候他也看不懂在幹嘛，做了實驗還是搞不懂，最好的方法之一是跳過，因為你可能遺漏了某些關鍵，先去別的地方看看，晚點回來也許就看得懂了。然後，有時候還是需要有一些想像力的。</p><p><strong>讀課程材料</strong></p><p>我知道很多課程的材料都很古老，或是知識含量比例低，但不論是 CSAPP 或是 CMU 的 CA 教學影片都非常緊湊且通篇無廢話，絕對就是非本科學生需要的，我認為都很值得一讀。</p><p>當然 jserv 的文章一定要讀，你不一定要滾瓜爛熟，但讀一遍總是要的，有個印象哪些東西被提到，想到還可以回來找。</p><p>後期你也需要 《Demystifying the Linux CPU Scheduler》和 <a href="https://sysprog21.github.io/cpumemory-zhtw/">每位程式開發者都該有的記憶體知識</a> ，拜託一定要讀，讀完之後要反覆驗證邏輯，你的推敲和反芻才是精華所在。</p><p><strong>使用好工具和好材料</strong></p><p>當我碩二下修這門課的時候，ChatGPT 已經非常成熟，在修課過程中透過 VSCode 搭配讀核心程式碼是非常有用的，絕對推薦。它的「幻想」能力有時候也有出其不意的效果。</p><p>善用 <a href="https://lkml.org/">lkml</a>，找到幾個你主修 subsystem 的重點改動，結合其他資料整理出為什麼當前的程式碼會被接受、現在的實作是為了什麼等等。</p><p>最後是去讀前人的筆記；這門課已經開了很久，而且 Linux Kernel 的更新通常是以數年為單位，就算是 2020 的筆記其中某一段體悟都可能可以協助解決你想破頭的問題，你只需要搜尋 「Linux 核心」+ 你的問題就可以找到相關筆記了。</p><h3><strong>結語</strong></h3><p>寫下我的心得是因為我顯然只是一個普通人，甚至可以說只是處在本科學生的及格線邊緣，但靠著在這堂課的努力也算是踏入 OS 和嵌入式的領域了。</p><p>也是因為這門課，我也幾乎把所有一線都面完了 （SMI 沒找我哭），其他一些軟體和系統廠也都面過，最後也找到嵌入式相關的職位，多位面試官也都認可我在 Linux 的能力和技能符合他們的要求，我想我應該符合 jserv 對於「翻身」的期待吧。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*VMJ1GTjjHAO1m4QcmgJleQ.png" /><figcaption>jserv 寫的書，我也在書中 EEVDF 一章有貢獻</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d507440f473" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/%E6%88%91%E7%9A%84-linux-kerenl-%E5%AD%B8%E7%BF%92%E8%B7%AF%E7%A8%8B-7d507440f473">我的 Linux Kerenl 學習路程</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review: An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-an-image-is-worth-16x16-words-transformers-for-image-recognition-at-scale-c08c1c81a211?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c08c1c81a211</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[vit]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 03:49:09 GMT</pubDate>
            <atom:updated>2022-08-29T08:20:36.208Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://arxiv.org/abs/2010.11929">An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</a></p><h3>Introduction</h3><p>本篇是 Vision Transformer 的濫觴，因著 Transformer 在 NLP 中的卓越表現，本文嘗試直接將 Transformer 應用於圖片；在此之前 Convolution 幾乎主宰電腦視覺領域，部分試圖整合 convolution 和 attention 機制的架構，部分試圖完全僅使用 attention，但因特化的 attention 運算的硬體支援不足外(註)，效果皆也遠不及傳統大型 Resnet。而本文提供一種使用大型資料集搭配 Transformer 架構，取代 CNN 架構的可能性。</p><h3>Method</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*RoloCt9P0vDezBSNa6ZmSw.png" /><figcaption>Model Overview</figcaption></figure><p>要讀懂如何將圖片輸入 Transformer 的關鍵是理解每一個部分的 tensor shape，以下我們搭配 <a href="https://github.com/lucidrains/vit-pytorch">lucidrains/vit-pytorch</a> 將每個步驟的 tensor shape 列出，並於此基礎上分析其物理意義。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*rgnlEKXF3uuARyQNxfaQwQ.png" /><figcaption>Input and Output of Attention Layers</figcaption></figure><p>首先，假定輸入圖片為 (224, 224, 3) ，我們將圖片打散為 N 張 patches，設 N = 14 * 14，所以我們會得到 196 張 patches (Fig.1 範例為 9 張)，每張維度 (1, 16, 16, 3)；即 x1_p, …, x196_p，P =224 / 14 =16。</p><p>故設 N=196, P = 16 得出 (1) 中各項的維度<br>x1_p, …, x196_p : (196, 768)<br>E : (768, 1024)<br>x_class : (1, 1024)<br>E_pos : (197, 1024)</p><p>得出 z_0 之維度 (197, 1024)。</p><p>而 (2) (3) 之中的 Multi-head Self Attention MSA 和 Multilayer perceptron MLP 之輸入輸出維度相同，故 (4) 取 197 序列的第一個z0_L 長度為 1024，故得到 y 之長度 1024。</p><h4>Inductive Bias</h4><p>中文翻譯作 “歸納偏置”，白話文來說，為在做出決策前，由於演算法 缺乏特定資訊做出決策，必須要作出假設，而每種演算法所傾向的假設不同，譬如 Convolution 的特性，導致 CNN 有著 局部性 Locality 和 平移不變性 Translation Equivariance 這兩種假設傾向，而剛好這種假設非常符合圖片資料，故原文中有這樣的描述：</p><blockquote>We note that Vision Transformer has much less image-speciﬁc inductive bias than CNNs. … In ViT, only MLP layers are local and translationally equivariant, while the self-attention layers are global.</blockquote><p>描述了 ViT 先天在處理圖片資料時，缺乏正確的假設傾向導致效能的下降。</p><h4>Hybrid Architecture</h4><p>作者另外提出了一種混合架構，不單單是把圖片打散為 patch 後輸入，而是使用 CNN 提取出的 feature maps；但其後的實驗能看到雖然在相對小模型時有優勢，但可以透過加大 ViT 模型得到相似與 Hybrid 精度。</p><h4>Fine-tune And Higher Resolution</h4><p>在 Fine-tune 時，當以下兩點改變時，要改變原先訓練的模型架構：</p><ol><li>Number of classes changed<br>當類別數量改變時，將 (3) 中，第 L 層原先訓練的 MLP 移除，並接上另一 fully connected layer，並以 0 初始化，維度為 (1024, new_num_classes) 即可。</li><li>Resolution of image changed<br>本文使用 (224, 224, 3) 圖片作為範例，當使用在圖片資料集 (384, 384, 3) 之上時，我們將固定 P = 16，因為 Transformer 可以處理變化的 N，但 E_pos 仍會受到不同 N 的影響，故這裡我們選擇對 E_pos 做 “2D interpolation” (我選擇理解為 Bilinear interpolation)。</li></ol><p>故當圖片為 (384, 384, 3)<br>N = 24, P = 16 得到</p><p>x1_p, …, x196_p : (576, 768)<br>E : (768, 1024)<br>x_class : (1, 1024)<br>E_pos : (577, 1024)</p><p>於是我們將原先的 E_pos (197, 1024) 內插為 (577, 1024) 即可。</p><h3>Experiments</h3><p>此處使用了三種大型資料集作為 pre-train dataset，包括 ImageNet 1K , ImageNet 21K 和 JFT，再使用如 ImageNet, ImageNet ReaL, CIFAR 等較小的資料進行 Fine-tune 實驗。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIXJIZlYzaVKNEbErbKU2w.png" /><figcaption>Comparisons of models pre-train on JFT and ImageNet21k</figcaption></figure><p>上表可以看出 ViT-H 在 accuracy 和 training efficiency 都遠超現有模型，尤其是在與也使用了 JFT 的 Noisy Student 做比較時，其可說是 CNN 模型在分類任務上的標竿。</p><p>另外也提供了 VTAB benchmark ，<a href="https://ai.googleblog.com/2019/11/the-visual-task-adaptation-benchmark.html">VTAB (Visual Task Adaptation Benchmark)</a> 是用於評估模型泛化在不同任務的能力，或我認為是能夠量化 model capacity；VTAB 提供一份訓練集使模型輸出 embedding representations，在使用訓練好的模型在 19 個不同的下游任務進行評估。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-65IjBRubL2Vd48Yxsvog.png" /><figcaption>VTAB results</figcaption></figure><h4>Pre-training Data Requirements</h4><p>本節談論了 ViT 的弱點，也就是在沒有 Image Inductive Bias 的狀況下，需要多少資料集才能學習到與 CNN 相似的能力；眾所周知 CNN 透過增加資料集的大小對於表現的提升是有限的，所以首先才有 Residuals Block 打造更深但有效的模型，才有能夠有效率的使用 JFT 的 Noisy Student 出現。</p><p>而 ViT 在大資料集有更好的效率，本文設計兩種實驗討論預訓練資料集大小對於 ViT 表現的影響。</p><ol><li>分別使用 ImageNet, ImageNet21k, JFT 作為預訓練資料集，並使用 weight decay, dropout 和 label smoothing：</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvF-p2lyn_xv9uaxOoN25Q.png" /></figure><p>可以看到隨著資料集的增大，ViT 的整體表性更好，但另外也有幾點觀察：</p><p>a. Large patch size 通常表現更差，可以看到 ViT-B/32 和 ViT-L/32 的表現都遜於它們 16 的版本。</p><p>b. 越小的 ViT 受到資料集增加的效益遞減非常大，雖然符合直覺，因較小的模型 model capacity 自然受限，但圖中從 ImageNet-21k 到 JFT-300M ，在資料集擴大 1000 多倍的狀況下，ViT-B 的表現幾乎沒有進步，甚至 ViT-B/32 有退化的跡象，有可能是受 regularization 影響。</p><p>c. CNN 也如同 ViT 一樣，在大資料集的狀況下，小型 CNN 一樣有退化的狀況。</p><p>2. 不使用任何 regularization ，將 JFT 分為四個大小 10M, 30M, 100M 及完整的 300M：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obhOmDoXduelYRyxqBvw3Q.png" /></figure><p>觀察與上圖相似，文中寫道</p><blockquote>This result reinforces the intuition that the convolutional inductive bias is useful for smaller dataasets, but for larger ones, learning the relevant patterns directly from data is sufficient, even beneficial.</blockquote><h4>Scaling Study</h4><p>本實驗皆使用 JFT 作為預訓練資料，在不同的資料集上 Fine-tune 固定 epoch (7 or 14)，討論在受限的運算資源下，模型訓練的效率。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOG3ZmFGy5DzIIvZguQEBQ.png" /></figure><p>左邊是除 ImageNet 外五種資料集的平均準確度，右邊是 ImageNet，更詳細的數據請見 Table 6。本次實驗有兩個觀察：</p><ol><li>ViT 在效率上全面勝過 ResNet BiT，幾乎是 2 – 4 倍有效率</li><li>Hybrids 在小資料時可能勝過 ViT，但大資料則否，符合前述實驗及直覺(CNN 在大資料集之限制)</li></ol><h4>Inspecting Vision Transformer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEhG_sFth0J0A7_qjRd97A.png" /></figure><p><strong>Center<br></strong>我們前面以 (224, 224, 3) 為例，E_pos 是 (197, 1024) ，除去x_class每一個 patch 都有一個長度 1024 的 E_n_pos ，所以每個 patch 之間的 positional embedding 可以求出 cosine similarity。</p><p>再來看中間圖片，先看第四行第四列的 patch ，也就是 (4, 4)，在上圖(4, 4)的小圖中，可以看到中間是最黃的，也就是最相關的，因為它自身與它自身的 positional embedding 當然是一模一樣的。</p><p>可以看出每個 patch 的 positional embedding 大致上會與周邊的，以及有垂直水平關係的 patch 的 positional embedding 有極大相關。</p><p><strong>Left<br></strong>左圖的意義是將前面所提的 (1) 式之 E 視覺化，可以看到這個 projection filter 產生了各種不同模式提取 patch 資訊。</p><p><strong>Right<br></strong>右圖所謂的 “attention distance” 很抽象，文中也沒有寫出計算式，但可以從文字中理解它的意義，首先</p><blockquote>This “attention distance” is analogous to receptive field size in CNNs.</blockquote><p>所以越大的 attention distance 意味著該 head 的 receptive field 越大，更能夠眾覽全圖；再來</p><blockquote>This highly localized attention is less pronounced in hybrid models that apply a ResNet before the Transformer, suggesting that it may serve a similar function as early convolutional layers in CNNs.</blockquote><p>當我們觀察 hybrid 模型的時候，由於使用了 Resnet，它提供了 CNN 的 inductive bias，所以更少的 head 去負責小的 recpetive field。如下圖右，幾乎沒有 head 是小於 40 的 mean attention distance 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*IquqTq5QvdnLb7cYjsKT6w.png" /></figure><p>最後猜測一下 attention distance 是如何被計算的 :</p><blockquote>Attention distance was computed for 128 example images by averaging the distance between the query pixel and all other pixels, weighted by the attention weight.</blockquote><p><strong><em>(Deprecated)</em></strong><em>依照這段文字，attention distance 與 MSA 中的 query 和權重有關，符合描述的應是 </em><em>QW^Q 與 </em><em>KW^K 相乘後得到一 (seq_len, seq_len) 的向量，這個向量的意義可理解為序列元素之間的相關性權重，原文中稱其為 attention weights，然後對其取平均，這是第一個可能。</em></p><p><strong><em>(Deprecated)</em></strong><em>往下計算，得到 </em><em>Attention(Q,K,V)即某個 head 的 self attention 矩陣 ( seq_len, num_feature) 計算出 (seq_len, seq_len) 的 cosine similarity 矩陣，取平均，這是第二種可能。</em></p><p>後來找到了關於 attention distance 的<a href="https://github.com/sayakpaul/probing-vits/blob/main/notebooks/mean-attention-distance-1k.ipynb">實作</a> (credit to <a href="https://github.com/sayakpaul">sayakpaul</a>) 如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K7Tjg65_GTo8bfmE" /><figcaption>Attention Distance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYl0SWIqLECb8TQLm7kXjA.png" /><figcaption>Code to compute Attention Distance</figcaption></figure><p>得到 Attention_i(Q,K,V) (num_patches, num_patches) 之後，乘以 distance_matrix (num_patches, num_patches)，自 0 到同樣行列的 num_patches 逐漸加大，譬如(0, 16, 32, 48…, 213.4666)，在對其平均得到一 scalar 則為該 head 之 attention distance。</p><p>直覺來看，越遙遠的地方有越大的 feature value (of Attention_i(Q,K,V)) 就會被認為是有更大 receptive field 的 head。</p><h4>Conclusion</h4><p>本篇為 Vision Transformer 的濫觴，不引入任何 CNN 之 Image Inductive Bias ，且以序列方式理解圖片，也能夠有很好的效果。</p><p>然而，本文使用了未開源 JFT-300M，認為 ViT 必須要在大型的資料集上訓練才能夠有與 CNN 匹敵的表現，但之後我們知道了，這只是訓練參數問題， DeiT 和 Swin Transformer 都能夠僅使用 ImageNet 1K 訓練就有極佳表現；接下來我們會就這兩篇續作探討。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c08c1c81a211" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-an-image-is-worth-16x16-words-transformers-for-image-recognition-at-scale-c08c1c81a211">Review: An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes of Clean Code from Uncle Bob]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/notes-of-clean-code-from-uncle-bob-2ac9949fe0de?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ac9949fe0de</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 06:28:14 GMT</pubDate>
            <atom:updated>2021-12-31T06:30:14.416Z</atom:updated>
            <content:encoded><![CDATA[<p>這是一篇不完整的 <a href="https://www.youtube.com/watch?v=7EmboKQH8lM">Clean Code — Uncle Bob</a> 速記，內文請與影片搭配使用。</p><h3>Lesson 1</h3><h4>Function</h4><ol><li>Function name as noun is terrible idea, should be verb, cause functions do things</li><li>Every line of a function should be at the same level of abstraction and that level should be one below the name (一個函式內僅有一種等級的物件，函式第一行物件即是該等級)</li><li>Smaller (smaller block, shorter name) is better</li><li>headline(all high level terms)→ abstract(slightly more detailed) → and increasing details until we get the bottom<br><strong>Allow the reader to escape early</strong><br><strong>How do people read news?</strong></li></ol><h4>Do one thing</h4><ol><li>how small it need to be? a function should do one thing. The one thing should be <strong>you can’t meaningfully extract another function from it.</strong></li><li>Sink in the sea of tiny little functions?No, you won’t. Name it properly.</li><li>“Class” consists of extracted functions that manipulate a set of variables.</li><li>The indent level of as function should not be greater than one or two(as the function would be large to have nests)</li></ol><h4>Arguments</h4><ol><li>A function more than 3 args is too complicated!</li><li>To much args → should be a object or contained</li><li>Don’t pass boolean variable into functions!</li><li>Don’t pass a “output args” for collecting outputs.</li><li>Code make you “double take” is rude, make sure your code is not surprising.</li></ol><h4>Avoid switch statements</h4><ol><li>Avoid switch statements, use Polymorphism.</li><li>Open close principle: open for extensions, close for modifications.</li><li>switch statement may result in a large amount of recompiling.</li><li>1:23:55 linking and loading</li></ol><h4>No side-effects</h4><ol><li>Side-effects pairs things should be finished in one function.</li><li>Convention:<br>Command(return void) must have a side effect<br>Query(return value) doesn’t</li></ol><h4>Exception, not returning error code</h4><h4>Don’t repeat your self</h4><ol><li>For multiple loop, JAVA lambda is a solution.</li></ol><h4>Structured Programming</h4><ol><li>Why did Dijkstra not want go-to</li><li>We don’t prove software correct like math, but we test it not incorrect like science.</li></ol><h3>Lesson 2</h3><h4>Comments</h4><ol><li>Comments are used to explain code if the code can’t explain itself.</li><li>Comments are not “pure good”, a comment is a failure for explain code by itself</li><li>Comments silently rot.</li><li>Write Bad code → Don’t comment it → Clean it!</li><li>If you can’t clean it, then comment it.</li><li>Always use name to explain code first, not comments.</li><li>Know Design Pattern!</li><li>Comments for DP could be informative</li><li>Comments for regex could be informative</li><li>Javados(like pydoc) are good, but they can lie.</li></ol><h4>Bad comments</h4><ol><li>Don’t mumbling to yourself with comments(what comments say should be very valid, local and simple.)</li><li>Don’t comment if code is simpler than the comment.</li><li>The place make the comments most readable is in the code, not HTML with Javadocs.</li></ol><h4>Format</h4><ol><li>number of line in File, Avg. 50 lines, most of files are within 100 lines, probably be good.</li><li>length of a line, 30–40 is probably good and shorter than 80.</li></ol><h4>Naming</h4><ol><li>A name that requires a comment, does not reveal it’s intent.</li><li>How long should a name be?<br>Variable: small scope, short name; large scope, long name.<br>Function, Class: large scope, short name; vice versa.</li><li>Naming need to be disambiguated</li><li>Avoid situations where code will break <strong>if a spelling error is fixed</strong></li><li>data vs dataProduct vs pd vs aProduct vs theProduct vs productInfo</li><li>getActiveAccount vs getActiveAccounts vs getActiveAccountInfo, which fn to call?</li></ol><h3>Lesson 3</h3><h4>I am your new CTO</h4><h4>Don’t ship shit.</h4><ol><li>When you release code, you will know it works, don’t guess it.</li></ol><h4>We will always be ready</h4><ol><li>Shorter sprint length might be better, cause we document well, test it, integrate it more frequently, and is ready to deploy it.</li><li>shippable, deployable, deliverable</li></ol><h4>Stable productivity</h4><ol><li>the longer the project goes, the slower you don’t get</li><li>if you do, because something is a mess</li></ol><h4>Inexpensive Adaptability</h4><ol><li>Be cheap and easy to make changes to the system. the cost of the change = k × the scope of the change</li><li>soft ware = changable product, if not , it’s hardware</li></ol><h4>Continuous Improvement of the system</h4><ol><li>code to get better with time.</li></ol><h4>Fearless Competence</h4><ol><li>if code need to clean, clean it, don’t leave it.Test it.</li><li>Get green little test buttom</li></ol><h4>QA will(should) find nothing.</h4><ol><li>Let QA automated</li></ol><h4>We cover for each other</h4><ol><li>how to make sure someone can cover for you? pairing, so code reviewing might consider to cancel</li></ol><h4>Honest Estimates</h4><ol><li>define the shape of what we don’t know</li><li>3 number: best case, nominal case, worst case</li></ol><h3>Lesson 4</h3><h4>You will say “no”</h4><h4>Test-driven development</h4><ol><li>Don’t write code until you write a test that fails, because the code doesn’t exist.</li><li>Don’t write more of a test that is sufficient to fail and “not compiling” is the failure.</li><li>Don’t write code that is sufficient to pass the failing test.</li><li>Test but don’t debug</li><li>Test code is the code example</li><li>testable ←→ decoupled</li><li>TDD is double entry bookkeeping, they both do it twice.</li><li>Mutation test</li><li>Production code → more general, Test code → more specific</li><li>Don’t run into the gold when writing test code, as long as you can.</li><li>Learn TDD externally at first.</li></ol><h3>Lesson 5</h3><ol><li>Architecture does not emerge from nothing.</li><li>Shape of Architectures might change, not fixed.</li></ol><h4>Goal</h4><ol><li>Software Architect is to minimize the human resources required to build and maintain software systems.</li><li>Measure of quality = k / Measure of efforts to meet requirement(inverse proportion)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ac9949fe0de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/notes-of-clean-code-from-uncle-bob-2ac9949fe0de">Notes of Clean Code from Uncle Bob</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed up Python numerical computation 660,000 times with Numba]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/speed-up-python-numerical-computation-65000-times-with-numba-4c056ef00405?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c056ef00405</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[numba]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Mon, 30 Aug 2021 12:45:27 GMT</pubDate>
            <atom:updated>2022-02-18T10:32:16.032Z</atom:updated>
            <content:encoded><![CDATA[<p>Python 在現代科學運算上扮演很重要的角色，尤其是 Machine Learning 領域，其核心是一連串的矩陣運算和最佳化理論；但受限於其 Interpreter GIL 和 動態類型語言等等，在中大型運算上的效能一直為人所詬病，所以 Numpy 應運而生，大部分使用 C 語言撰寫使 Numpy 能夠較少的受上述兩點影響，許多常見且具有較高效能的 Python package 都是奠基於 Numpy。</p><p>但很多應用顯然不滿足於此，Numpy 還是太慢了，如果我們可以將某部分高運算需求的模塊編譯，就能夠大幅加速應用。本文討論的 Numba 是一種 <strong>Just-In-Time Compilation</strong>，介於如 C 的 <strong>Ahead-of-Time</strong> <strong>Compilation </strong>和如 Python 的 <strong>Interpreter</strong> 之間；保留 Python 開發靈活性的同時，不需要深入最佳化 CPython Interpreter 也能夠大幅加速 Python；此外，還是一種異構計算，可以同時使用 CPU 與 GPU 運算，對於特定的應用，可以完全解放硬體性能。</p><p>本文提出一個範例實驗，設計一套演算法將點狀 (scatter) 資料轉為圖片(矩陣, grid)資料，分別使用 Python, Numpy, Numba, Numba CUDA 實現，並比較效能。</p><h4>Sample Data</h4><p>以下的程式碼產生五萬個點，其資料型式以三個向量組成，分別為 x 座標、y 座標以及其上的值；值的部分為 x, y 組成的 cos 函數：</p><pre><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np<br>from</strong> <strong>matplotlib</strong> <strong>import</strong> pyplot <strong>as</strong> plt</pre><pre>x = np.random.randint(1, 10, 50000) + np.random.random(50000)<br>y = np.random.randint(1, 10, 50000) + np.random.random(50000)<br>v = np.cos(x - y)<br>fig = plt.figure(figsize=(16, 12))<br>ax = plt.axes()<br>ax.scatter(x, y, c=v, cmap=&#39;Greens&#39;)</pre><p>我們亦得到下圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*zeAK4bBrQFFVczOfmMadwg.png" /><figcaption>Example Data</figcaption></figure><p>這個點資料將做為演算法的輸入，轉換成矩陣型態，也就是圖片資料；圖片資料是在一個矩陣之上，每一個 pixel 儲存一個值，若演算法正確，我們應該能夠看到相同於上圖的矩陣(圖片)。除了正確性外，此處我們也要兼顧效能；點資料時常用於高精度的形式，如 Time of Flight 的 LiDAR，一份點資料很輕易就內含上百萬個點；但事實上我們很可能僅需要取很小一部分子集，如一張 320×320 的圖片(102400個點)就能得到足夠的資訊應用到其他演算法上，此外，轉換成圖片能夠讓我們輕易的使用傳統的電腦視覺演算法，或是 Object Detection 以及 Segmentation 等等。</p><p>以下演算法按照不同場景和應用可能有些細節還需要調校，但核心邏輯是將 grid 中的每一格在 scatter data 位置計算出來，並以 L2 求最近座標的點之值填入對應的格子。</p><p>以下實驗為了符合實際場景，我們改採用<strong>一百萬個點，並投射到 (320, 320) 的矩陣上</strong>。</p><h4>Python</h4><pre><strong>def to_image</strong>(image_np, x, y, value, <br>             width, height, dist_threshold):<br>    x_min, y_min = min(x), min(y)<br>    x_max, y_max = max(x), max(y)<br>    width_interval = (x_max - x_min) / width<br>    height_interval = (y_max - y_min) / height<br>    MAX_DISTANCE = 10</pre><pre>    num_points = len(x)<br>    <br>    <strong>for</strong> row <strong>in</strong> range(width):<br>        x_point = width_interval * row + x_min<br>        <strong>for</strong> col <strong>in</strong> range(height):<br>            y_point = height_interval * col + y_min</pre><pre>            min_dist = MAX_DISTANCE<br>            min_dist_idx = 0<br>            <strong>for</strong> i <strong>in</strong> range(num_points):<br>                dist = ((x[i] - x_point) ** 2) + \<br>                       ((y[i] - y_point) ** 2)<br>                <strong>if</strong> min_dist &gt; dist:<br>                    min_dist_idx = i<br>                    min_dist = dist</pre><pre>            <strong>if</strong> min_dist &gt; dist_threshold:<br>                image_np[row, col] = 0<br>            <strong>else</strong>:<br>                image_np[row, col] = value[min_dist_idx]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhTYupL4PjWsJP45UVSMgQ.png" /><figcaption>CPython result of line profiler</figcaption></figure><p>使用原生 Python 的問題很明顯，因為沒有 vectorization 運算，所以 24行後for i in range(num_points) 以下的運算耗時非常久，這一段在 Numpy 可以輕易透過 np.argmax 和向量相加加速。</p><h4>Numpy</h4><pre><strong>def</strong> <strong>to_image_np</strong>(image_np, x, y, value,<br>                width, height, dist_threshold):<br>    width_interval = (x.max() - x.min()) / width<br>    height_interval = (y.max() - y.min()) / height<br><br>    image_np = np.empty((width, height), dtype=np.float32)<br>    shift_x = x - x.min()<br>    shift_y = y - y.min()</pre><pre><strong>    for</strong> i <strong>in</strong> range(width):<br>        x_dist_square = np.power(shift_x - (width_interval * i), 2)<br>        <strong>for</strong> j <strong>in</strong> range(height):<br>            y_dist_square = np.power(shift_y - \             <br>                                     (height_interval * j), 2)</pre><pre>            dist_square = x_dist_square + y_dist_square<br>            nearest_points_idx = np.argmin(dist_square)<br>            <strong>if</strong> dist_square[nearest_points_idx] &gt; dist_threshold:<br>                image_np[i, j] = 0<br>            <strong>else</strong>:<br>                image_np[i, j] = value[nearest_points_idx]</pre><p>透過 line profiler ，我們大致可以觀察到 numpy code 的效能瓶頸：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSPR7qaMwAdK7vOLFly7yw.png" /><figcaption>Numpy result of line profiler</figcaption></figure><p>主要集中在第 49 行計算 y_dist_square ，佔執行時間的將近九成；但 Per Hit 使用的時間並不比 x_dist_square 長，主要是因為運算次數達 102400 次。</p><p>而單次執行時間最久的為 47 和 49 的 np.power 與向量減去常數，這兩者都無法透過演算法再加速，僅能尋求底層的最佳化了。</p><p>我認為這樣的場景就是非常適合引入 Numba ：<br>1. 大型矩陣參與運算<br>2. 效能瓶頸不在於單一(或不嚴謹的說，atomic)複雜耗時的指令<br>3. for loop 之間獨立處理元素</p><p>以上條件讓使用者將 Numpy 改寫為 Numba 非常簡單，幾乎不需處理平行化的衍生議題，就能透過廣開執行緒的方式大幅加速應用。</p><h4>Numba</h4><p>事實上 njit 可以使用的更簡單，譬如僅加上 @njit ，但加上型別宣告可以更快速啟動 JIT 以及編譯最佳化，對於速度會有所幫助。</p><p>若型別錯誤，編譯警告會直接顯示輸入的型別是什麼，加上和 Numpy 還有部分兼容，甚至還可以使用 np.argmin ，可以說是相當親近 Python 使用者。</p><pre><strong>import</strong> <strong>numba</strong><br><strong>from</strong> <strong>numba</strong> <strong>import</strong> njit, prange<br><br><br>@njit((),<br>      numba.types.Array(numba.float64, 1, &#39;C&#39;),<br>      numba.types.Array(numba.float64, 1, &#39;C&#39;),<br>      numba.types.Array(numba.float64, 1, &#39;C&#39;),<br>      numba.int64, numba.int64, numba.float64),<br>      parallel=<strong>True, </strong>fastmath=<strong>True</strong>)<br><strong>def</strong> <strong>to_image_signature</strong>(image_np, x, y, value, <br>                       width, height, dist_threshold):<br>    width_interval = (x.max() - x.min()) / width<br>    height_interval = (y.max() - y.min()) / height<br>    shift_x = x - x.min()<br>    shift_y = y - y.min()</pre><pre>    image_np = np.empty((width, height), dtype=np.float32)<br>    <strong>for</strong> i <strong>in</strong> prange(width):<br>        x_dist_square = np.power(shift_x - (width_interval * i), 2)<br>        <strong>for</strong> j <strong>in</strong> prange(height):<br>            y_dist_square = np.power(shift_y - \<br>                                     (height_interval * j), 2)</pre><pre>            dist_square = x_dist_square + y_dist_square<br>            nearest_points_idx = np.argmin(dist_square)<br>            <strong>if</strong> dist_square[nearest_points_idx] &gt; dist_threshold:<br>                image_np[i, j] = 0<br>            <strong>else</strong>:<br>                image_np[i, j] = value[nearest_points_idx]</pre><h4>Numba CUDA</h4><p>在使用 numba.cuda 前，要稍微介紹 CUDA 中 grid, block 和 thread 的概念。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*BodUB4CmD02SrGWx.png" /><figcaption>Thread Batching</figcaption></figure><p>這張圖的重點為，Thread ⊆ Block ⊆ Grid ⊆ GPU，GPU 中執行指令(kernel)的最小單位為 Thread。另一個概念是 Warp，像是 Thread 的小組別 (Block 像是宿舍房間)，一個 Warp 會含有 32 個在同一個 Block 的 Thread，多數時候；而當該 Block 的 Thread 數量小於 32 時，它們會被歸類在一個 Warp，所以多數時候也是 Thread ⊆ Warp ⊆ Block。</p><pre><strong>from</strong> <strong>numba</strong> <strong>import</strong> cuda</pre><pre>@cuda.jit<br><strong>def</strong> <strong>to_image_numba_cuda</strong>(image_np, x, y, value, <br>                        width, height, x_min, y_min, <br>                        x_max, y_max, dist_threshold):<br>    width_interval = (x_max - x_min) / width<br>    height_interval =  (y_max - y_min) / height</pre><pre>    MAX_DISTANCE = 10<br>    start_x, start_y = cuda.grid(2)<br>    grid_x, grid_y = cuda.gridsize(2)<br><br>    num_points = x.shape[0]<br>    <br>    <strong>for</strong> row <strong>in</strong> range(start_x, width, grid_x):<br>        x_point = width_interval * row + x_min<br>        <strong>for</strong> col <strong>in</strong> range(start_y, height, grid_y):<br>            y_point = height_interval * col + y_min</pre><pre>            min_dist_idx = 0<br>            min_dist = MAX_DISTANCE<br>            <strong>for</strong> i <strong>in</strong> range(num_points):<br>                dist = ((x[i] - x_point) ** 2) + \<br>                       ((y[i] - y_point) ** 2)<br>                <strong>if</strong> min_dist &gt; dist:<br>                    min_dist_idx = i<br>                    min_dist = dist</pre><pre>            <strong>if</strong> min_dist &gt; dist_threshold:<br>                image_np[row, col] = 0<br>            <strong>else</strong>:<br>                image_np[row, col] = value[min_dist_idx]</pre><p>其中 cuda.grid 回傳整個 grid 中 thread的絕對位置，如 start_x = 0, 1, 2, … 即為第一個 block 的第一個 thread、第二個 thread、第三個 thread等；cuda.gridsize 則是 整個 grid 當中 thread的數量。</p><h4>Performance</h4><p>以下數字由 AMD Ryzen 3900X 12-Core Processor 及 RTX 2080 Ti on CUDA 11.2 得到；</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*KGi35BoTgpbi54_FaoE7vQ.png" /><figcaption>Time Cost of each tool</figcaption></figure><p>在處理百萬個數值，並搜尋近似的 320×320 圖片的問題下，原生 Python 慢到幾乎不可能使用(註)；而 Numpy 則需約半小時，雖有顯著進步，但對於可能的即時運算場景還是捉襟見肘。</p><p>僅使用 CPU 的 njit 以簡易的平行化方案，有超出 10 倍於 Numpy 的加速；而 Numba CUDA 包含將資料 host copy to device , initialize cuda array , compilation 等等，僅需不到半秒鐘，運行時間太短連使用 nvprof 都有困難。</p><p>最終，相較於 Python ，Numba CUDA 能夠得到近 660,000 倍的速度提升。</p><h4>Conclusion</h4><p>Python 的易用性是其最大的優勢也是詛咒，雖然 Guido van Rossum 放話要為 CPython 解決效能問題，但面對越來越龐大精細的資料和複雜的演算法終究是杯水車薪；Numba 雖僅能治標，但藥效強勁，Python 使用者都應該要對其有基本的認識。Numba 值得討論的和坑還很多，如 CUDA stream , CUDA BlockDim , ThreadDim 的配置、使用 nvprof 和 nvvp 做效能調校，以及深入其原理的最佳化技巧等等，但篇幅龐大且艱深，就先交給明天吧。</p><p>除了 Numba ，如 Pypy , Cython 或是近日開源的 Triton 都值得使用 Python 且想為科學計算加速的使用者研究，一併推薦大家。</p><h4><strong>Reference</strong></h4><p><a href="https://numba.pydata.org/numba-doc/latest/index.html">Numba documentation</a></p><p><a href="https://kheresy.wordpress.com/2008/07/09/cuda-%E7%9A%84-threading%EF%BC%9Ablock-%E5%92%8C-grid-%E7%9A%84%E8%A8%AD%E5%AE%9A%E8%88%87-warp/">CUDA 的 Threading：Block 和 Grid 的設定與 Warp</a></p><p><a href="https://curiouscoding.nl/phd/2021/03/24/numba-cuda-speedup/">28000x speedup with Numba.CUDA</a></p><p><a href="https://lulaoshi.info/gpu/python-cuda/cuda-intro.html">初识GPU编程Permalink</a></p><p>註: CPython 實在是太久了，在將近十個小時候忍不住停下來看了狀況；此 244000s 是按照 line profiler 以比例大致計算。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c056ef00405" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/speed-up-python-numerical-computation-65000-times-with-numba-4c056ef00405">Speed up Python numerical computation 660,000 times with Numba</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review: Meta Pseudo Labels — Series 3 of 3]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-meta-pseudo-labels-series-3-of-3-1a00be6380e7?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a00be6380e7</guid>
            <category><![CDATA[meta-learning]]></category>
            <category><![CDATA[semi-supervised-learning]]></category>
            <category><![CDATA[pseudo-labeling]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 15:39:20 GMT</pubDate>
            <atom:updated>2021-11-09T14:53:37.976Z</atom:updated>
            <content:encoded><![CDATA[<h3>Review: Meta Pseudo Labels — Series 3 of 3</h3><p><a href="https://arxiv.org/abs/2003.10580">Meta Pseudo Labels</a></p><p>這是 Google Self-training 系列的最後一篇，這個系列第一篇提出了一個新的Teacher-student 的訓練架構：加入適當的噪聲後，在不斷的迭代訓練下，能夠不斷的推昇準確度。</p><p>系列二則是討論了 pre-training, train from scratch, noisy student 三種訓練架構的優缺，以及適合的應用場景。</p><p>系列三，也就是本篇，檢討了系列一的缺點，提出了一個改良版，使 Teacher Model 能隨著 Student Model 的表現同時被訓練，更進一步提昇準確度，並成為 ImageNet 的榜首。</p><h3>Introduction</h3><p>Noisy Student 是透過已經訓練好的 Teacher Model 輸出某一未被標籤圖片的偽標籤，讓 Student Model 以此標籤為目標預測該圖片結果，當擁有遠多於標籤資料的大量未標籤資料，卻也想取用該未標籤資料的訊息時，Noisy Student 是很棒的選擇。</p><p>但問題也十分明顯：如果 Teacher Model 輸出的偽標籤不準確呢？有兩種可能，以 ImageNet 為例：</p><ol><li>就算以本篇取得的 ImageNet SOTA 作為 Teacher Model，不過也是 90.2% 的 Top1 Acc. 而已，還是有 10% 的預測是錯誤的。即 Confirmation Bias。</li><li>該未標籤資料帶有 Teacher Model 未曾見過的模式，譬如說加上某些未知的 Augmentations。</li></ol><p>所以 Noisy Student 的缺點是： Teacher Model 是固定的、不隨新加入的資訊(未標籤資料) 訓練！</p><blockquote>Despite the strong performance of Pseudo Labels methods, they have one main drawback: if the pseudo labels are inaccurate, the student will learn from inaccurate data. As a result, the student may not get significantly better than the teacher. This drawback is also known as<strong> the problem of confirmation bias</strong> in pseudo-labeling.</blockquote><blockquote>This drawback is also known as the problem of confirmation bias in pseudo-labeling. In this paper, we design a systematic mechanism for the teacher to correct the bias by observing how its pseudo labels would affect the student.</blockquote><p>那下個問題便是，如果 Teacher Model 要被訓練，要以什麼訓練他呢？</p><p>由於新加入的資料是未標籤資料，當然不可能使用 Supervised training ，況且這也會失去 Noisy Student 原先的立意。答案很直觀：老師當然是透過學生的表現去被訓練。當學生表現的好時，表示老師給出的教學很正確，表現不好時則否（個人認為，這邊有嗅到一絲絲 Reinforcement Learning 的味道）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*MeGTLfEery1BcU4gGDIaLA.png" /></figure><h3>Meta Pseudo Labels</h3><p>這一章節討論了 Loss Function 的設計，經過一連串 model and loss dependency 的推導後，我們可以得出：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*_2xzdN_VA8XTvOuhaxSCJg.png" /></figure><p>事實上，<br>Student Model 最終在 Labeled dataset 上要能得到最小的 Loss，<em>看似要最佳化的是 Student Model 的參數，但應該是要最佳化 Teacher Model 的參數才對！因為 Student Model 是 Teacher Model 參數的函數！</em></p><p>但由於他們的相依性實在太複雜，根本無法微分，所以論文採用實務上可微分的近似解(ideas from <a href="https://arxiv.org/abs/1806.09055">Darts: Differentiable architecture search, Hanxiao Liu et al.</a> and <a href="https://arxiv.org/abs/1703.03400">Model agnostic meta-learning for fast adaptation of deep networks, Chelsea Finn et al.</a>)：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*8YJmYrI28yEATJ7sXsrasw.png" /></figure><p>所以有了，</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*4vkRMY8Us65_Jyb8TuJv6w.png" /></figure><p>也就是說，每次 Student Model 使用 unlabeled data 上的 Loss 更新參數後(使用 Teacher 提供的 pseudo label )，然後對 labeled data 運算 Loss, 作為 Teacher Model 的 Loss，去更新 Teacher Model 的參數。</p><h4><strong>Teacher’s auxiliary loss</strong></h4><p>除了使用來自於 Student Model 回饋的損失函數外，也嘗試使用其他多種損失函數一起訓練，譬如直接對 Labeled data 訓練得到的 Cross Entropy，以及 unsupervised learning 的 UDA (<a href="https://arxiv.org/abs/1904.12848">Unsupervised Data Augmentation</a>)。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*M1OlZmCtmcP9r2T4LcQgNQ.png" /><figcaption><strong>Auxiliary Loss</strong></figcaption></figure><h3>Small Scale Experimen</h3><h4><strong>TwoMoon Experiment</strong></h4><p>設置了經典的 Two Moon 資料集，雖然僅僅是二維的資料，卻表現出可視的複雜 manifold。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*nCdCquwDyzs615ahLm0FXA.png" /></figure><blockquote>Pseudo Labels uses the bad classifier from Supervised Learning and hence receives incorrect pseudo labels on the unlabeled data.</blockquote><blockquote>Meta Pseudo Labels, on the other hand, uses the feedback from the student model’s loss on the labeled instances to adjust the teacher to generate better pseudo labels.</blockquote><p>此段的用意很明顯，就是當使用了一個 &quot;<em>bad classifier</em>&quot; 當作老師，Meta Pseudo Labels 很明顯的能夠表現更好。</p><h4>CIFAR-10–4K, SVHN-1K, and ImageNet-10% Experiments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxTxHdC8SYY7KexmJcfL9A.png" /><figcaption>: Image classification accuracy on CIFAR-10–4K, SVHN-1K, and ImageNet-10%</figcaption></figure><p>這一小節並沒有什麼營養，僅是表示在同樣架構的模型和訓練條件下，Meta Pseudo Labels 在小規模數據上確實是行。</p><blockquote>..., Meta Pseudo Labels has achieved the best accuracies among the same model architectures on all the three datasets...</blockquote><h4>ResNet-50 Experiment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*1R8GqspYACa144aGXIAzUA.png" /><figcaption>Top-1 and Top-5 accuracy on ImageNet with ResNet-50</figcaption></figure><p>同上節，展示得到了幾乎在各方法中最好的 ResNet-50，在 Top-5 稍稍惜敗 FAIR 的 Billion-scale ，但 FAIR 使用的 3.5B labeled Instagram 確實還是比 JFT 大了不少。</p><h3>Large Scale Experiment: Pushing the Limits of ImageNet Accuracy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZZgKOJocJ0_AxNIw9gztg.png" /><figcaption>Top-1 and Top-5 accuracy on ImageNet</figcaption></figure><p>Meta Pseudo Labels 超越 Noisy Student 將近 2% Top-1 Acc. ，但這是有非常大代價的。</p><p>在 Model parallelism 小節中，說明了同樣在 2048 TPUv3 cores 上，即便在使用了 model parallelism 後，Meta Pseudo Labels 仍花費了 11 天訓練 EfficientNet-L2；而 Noisy Student 中則僅花費 6 天，原因之一是 Noisy Student 是 fixed teacher，它可以將訓練圖片先運算儲存為 logits，故在記憶體使用及運算時間上都遠遠少於本篇。</p><h4>A lite version of Meta Pseudo Labels</h4><p>顯然，原版的 Meta Pseudo Labels 不論在資料集、運算機器上都遠非一般人能夠想像，佛心來著的 Google 提供了另一個 &quot;lite version&quot;：</p><p>首先，JFT-300M 並非開源資料，於是替算成「僅有」100M 圖片的 YFCC 資料集作為 unlabeled data。</p><p>此外，訓練架構嘗試使用 fixed teacher 的想法，使用原始 Teacher Model 對所有 unlabeled data 計算出 logits 並儲存。在 Student Model 的訓練階段，使用一個簡單的模型，如 MLP 作為 Teacher Model 。</p><p>這樣的架構不但同樣能夠得到原先強大 Teacher Model 的資訊，也能夠在訓練階段，讓 MLP 模型根據 Student Model 的表現調整 logits。</p><p>這樣的訓練架構和 Noisy Student 非常像似，也承襲 Meta Pseudo Labels 的優點，我個人認為，這算是本篇論文的一大亮點。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRf-pN20awe8u9BQorJLVw.png" /><figcaption>Benchmark of Reduced Meta Pseudo Labels</figcaption></figure><p>不過，還有一些值得討論，譬如：</p><ol><li>如果將原版的 Meta Pseudo Labels 使用 YFCC 100M 作為比較，我們能夠看到將原先的 Teacher Model 換成 MLP 後，會損害多少表現。</li><li>如果使用一個 ResNet-50 而非 MLP 呢？</li><li>綜合以上兩點，使用的 unlabeled dataset 大小和 Reduced Teacher Model 對於 Meta Pseudo Labels 的影響是什麼？</li></ol><p>總之，對於運算力庶民的我來說，&quot;Reduced&quot; Meta Pseudo Labels 反而是我想了解更多的部份。</p><h3>Related Works</h3><p>這一節有價值的部份是闡述了 Pseudo Labels 與其他演算法的差異或本片的借鑑，如</p><ol><li>與 Self-supervised Learning 的差別是，對於使用 labeled data 的 SSL，如 <a href="https://arxiv.org/abs/1803.07728">Rotation</a>，<a href="http://1603.09246">Jigsaw Puzzle</a> 和 <a href="https://arxiv.org/abs/1806.09594">Colorization</a> etc.，模型表現將受限於資料量。對於不使用 labeled data 而透過資料本身帶有的資訊去訓練的演算法，如 SimCLR，Meta Pseudo Labels 這種透過強烈先驗 (Teacher Model) 給出的資訊，顯然更勝於僅使用資料本身的 trivial information。</li></ol><blockquote>First, the student in Meta Pseudo Labels never learns directly from labeled data, which helps to avoid overfitting, especially when labeled data is limited. Second, the signal that the teacher in Meta Pseudo Labels receives from the student’s performance on labeled data is a novel way of utilizing labeled data.</blockquote><p>2. 與 Knowledge Distillation，共同之處是 soft labels，用更好的方式來設計 soft labels 都是雙方達成更好表現的關鍵。只不過同大多數演算法， Knowledge Distillation 的 soft labels 通常都是不隨訓練變動的，這是與 MPL 的不同之處。</p><blockquote>Both of these methods can be seen as adjusting the labels of the training examples to improve optimization and generalization.</blockquote><p>3. Bi-level optimization，中文通常翻作雙層規劃或雙層最佳化，簡單但不嚴謹的定義是「如果下層模型的輸出是上層模型的參數」，就可以被理解為 Bi-level optimization。這個比較少在 Deep Learning 的領域中看到，除了 meta-learning 領域，而 MPL Gradient approximation 是基於 Bi-level optimization 所得出的結果。</p><h3>Appendix</h3><p>本篇論文的附錄也是非常精彩，如 A 有關於 Teacher Model 和 Student Model 近似 Loss function 的推導，C 則是為了打破 SOA 的hyper parameter tuning，D 則是由演算法觀點分析 Meta Pseudo Labels ，值得一讀</p><h4>Appendix D</h4><p><strong>D.1. Visualizing the Contributions of Meta Pseudo Labels</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*recyuW8YUcqfAeYHy1nAUA.png" /><figcaption>Contributions of MPL (Meta Pesudo Labels)</figcaption></figure><p>文中提到這裡有兩個觀察：</p><ol><li>在少量訓練樣本下(此處使用 ImageNet 10%)，MPL 是很好的 Regularization，甚至勝過 RandAugment。在 Supervised 情境下，使用 MPL 是將 labeled data 作為 unlabeled data，並輸出 soft label，如同 label smoothing 一樣，只是 label smoothing 的函數是固定的，而 MPL 則隨著學生表現持續更新。</li><li>在少量訓練樣本下，UDA 遠勝過 Supervised + MPL + Finetune，MPL + UDA 更是強強聯手，讓已經很強大的 UDA 再躍昇 5.25% top-1 acc.。</li></ol><p><strong>D.2. Meta Pseudo Labels Is An Effective Regularization Strategy</strong></p><p>這一小節則是將 MPL 作為 Regularization ，不過是選用兩個小資料集，前一小節勝過 RandAugment，比較令人驚訝。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*LHHfL11de7cZuEyqMBqWPQ.png" /><figcaption>MPL as Regularization on CIFAR-10 and SVHN</figcaption></figure><p><strong>D.3. Meta Pseudo Labels Is a Mechanism to Addresses the Confirmation Bias of Pseudo Labels</strong></p><p>MPL 的另一個重點，就是要解決 Noisy Student Confirmation Bias 問題，即，Teacher Model 若非百分之百準確，Pseudo Labels 終究與真實答案有若差，自然 Student Model 的學習也會有落差。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*wvzmQy3TjAXu-QKjilhf4g.png" /><figcaption>Training accuracy of Meta Pseudo Labels and of supervise learning</figcaption></figure><p>在 CIFAR-10 與 ImageNet-10% 中可以看到不同的現象，前者為慢於 Supervised 收斂，而後者則是快於。本作認為，這兩種行為都是為了使 Student Model 更好的學習，避免 confirmation bias。</p><ol><li>CIFAR-10<br>因為 CIFAR-10<strong> 標記資料非常少</strong>，如果Teacher Model太快的收斂(像是 Supervised 一樣)，就無法 generalize to unlabeled data並給出可靠的 pseudo labels。而上圖中，Teacher and Student 都收斂得很慢，Student Model 顯然「不同意」pseudo labels，導致 Teacher Model 不斷修正 pseudo labels，又更拉長 Student Model 收斂的時間。長的收斂時間避免了 confirmation bias。</li><li>ImageNet 10% <br>Student Model 的快速收斂，甚至還要快於 Teacher Model，後者只好快速的學習，兩邊相輔相成。文中並懷疑 Supervised 是 overfitting，若以 Supervised 作為 Teacher Model (即 pseudo labels)，則會導致confirmation bias。</li></ol><p>我個人感覺這一節有點牽強，或是說明不足，看似能夠自圓其說，但<strong>缺少 Testing Acc. 的比較</strong>，為什麼 ImageNet10% 上的 Supervised 是 overfitting ，而 CIFAR-10 上就不是呢（如果是，表示 MPL 也 overfitting 了）？只因為 MPL 讓 Teacher and Student Model 花費更多時間收斂？過幾天再來重新看看這章節，如果對原文有其他理解，也請留言指導。</p><p><strong>D.4. Meta Pseudo Labels with Different Training Techniques for the Teacher</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*QZBGBD_7LdjdjSpl7MU0qw.png" /><figcaption>MPL with other training techniques</figcaption></figure><p>本小節指出， MPL 與現行常用的訓練技巧皆可共用。圖中為 Student Model 之 acc.。</p><p><strong>D.5. Meta Pseudo Labels with Different Amounts of Labeled Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*Jrk4BvxU3ylep-cTY8CMwg.png" /></figure><h3>Discussion</h3><p>近日另有一篇相關論文為 <a href="https://arxiv.org/abs/2106.05237">Knowledge distillation: A good teacher is patient and consistent</a> ，與本篇共同闡述了 trade-off of model scale and performance ：</p><ol><li>透過 Meta Pseudo Labels，相似規模的模型，可以透過 Meta Pseudo Labels 達到超越該規模模型常規的精確度。</li><li>透過 &quot;Patient Teacher&quot; ，有希望讓輕量模型達到大規模模型的表現。</li></ol><p>雙方的目的不同，但都是為了提升 performance / cost ，期望這系列論文能夠融合兩種觀點，在架構及訓練上釐清如何產生更有效率的模型。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a00be6380e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-meta-pseudo-labels-series-3-of-3-1a00be6380e7">Review: Meta Pseudo Labels — Series 3 of 3</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review: Rethinking Pre-training and Self-training — Series 2 of 3]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-rethinking-pre-training-and-self-training-series-2-of-3-737afae25317?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/737afae25317</guid>
            <category><![CDATA[pre-training]]></category>
            <category><![CDATA[imagenet]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[self-training]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 12:03:16 GMT</pubDate>
            <atom:updated>2021-02-27T12:42:46.829Z</atom:updated>
            <content:encoded><![CDATA[<h3>Review: Rethinking Pre-training and Self-training — Series 2 of 3</h3><p><a href="https://arxiv.org/abs/2006.06882">Rethinking Pre-training and Self-training</a></p><p>Pre-training 一直是 Computer Vision 愛用的技術，一般認為它能夠非常快的配適在不同資料集（以及任務）上，早年甚至認為它在任何條件下都能夠快速的達到與 train-from-scratch 相等的準確度，甚至認為在相同的 iteration 之下，前者會勝過後者。</p><p>直到 2018 年底何恺明的 <a href="https://arxiv.org/abs/1811.08883">Rethinking ImageNet Pre-training</a> 告訴我們，Pre-training 事實上不會對模型的準確度有任何幫助，唯一優點僅是比較快收斂而已，但這個優點仍足夠我們大量的使用 Pre-training。</p><p>And here we are.</p><p>Rethinking Pre-training and Self-training 在考量資料集大小、不同任務、不同 Data Augmentation 強度後認為，在各項準確度上，<strong>Pre-training 不但無法勝過 train-from-scratch ，甚至會傷害模型準確度</strong>，而 Self-training 在單次的訓練終究能勝過 train-from-scratch。</p><p>這篇會重新闡述 Pre-training 的價值所在，以及 Self-training 的驚人成果。</p><h3>Introduction</h3><p>Pre-training 是一項很普遍的技巧，為的是希望在一個資料集上訓練過的模型，能夠在各方面幫助另一個資料集的訓練。直到何恺明的著作表明，ImageNet Pre-training 很可能無法幫助 Object Detection 和 Segmentation。</p><p>而在同樣的場景下，在 Self-training 上使用 ImageNet 幫助 COCO ，則是先需要 Teacher model trained on COCO ，並輸入 ImageNet 作 pseudo label，與 human label 共同訓練 Student。</p><p>因為後者取得的巨大成功，我們將來比較此二者的差異。</p><p>結果表明：<br>1. 依照情境， Pre-training 的準確度不但無法超越 Random Init train-from-scratch ，還可能會傷害表現</p><p>2. 當擁有的資料集越大，Pre-training 造成的傷害越大</p><p>3. 當使用的 Data Augmentation 越強力，Pre-training 造成的傷害越大</p><p>4. Self-training 在任何的情境下，(無迭代) 皆比 Pre-training 甚至 Random Init 更為準確</p><p>5. 使用 ImageNet 應用到 COCO 或 PASCAL，第四點亦成立</p><p>然而，Pre-training 並非就此被打入冷宮，在少資料量如 PASCAL 仍有媲美 Random Init 的準確度，以及比起 Self-training 需要長久時間且 computing-intensive，Pre-training 可以有 1.3 - 8 倍的加速。</p><h3>Methodology</h3><h4>Data Augmentation</h4><p>在本篇的實驗中，使用四種強度的 Augmentation<br>1. Augment-S1: Flips and Crops Only<br>2. Augment-S2: AutoAugment, Flips and Crops<br>3. Augment-S3: Large Scale Jittering, AutoAugment, Flips and Crops<br>4. Augment-S4: Large Scale Jittering, RandAugment, Flips and Crops</p><p>而在何恺明一篇中，僅使用 Flips and Coprs Only。</p><h4>Pre-training</h4><p>針對 Pre-training model 除了一般使用的 EfficientNet-B7 + AutoAugment 達成 84.5% on ImageNet 外，亦使用了 EfficientNet-B7 +NoisyStudent 達成 86.9% 的模型，這邊稱作 ImageNet++。</p><p>需要特別注意的事情是，<strong>論文中所有的 Student 皆是 Init by Teacher</strong>，而凡是有使用 Pre-trained 的 Self-training ，皆是指 <strong>Teacher 使用 Pre-trained model 並在 COCO 或 PASCAL 上訓練</strong>。</p><p>而在何恺明一篇中，僅使用 ResNet-50 及 ResNet-101。</p><h4>Self-training</h4><p>Self-training 的設置則是先使用 COCO train-from-scratch 取得 Teacher Model，再使用 Random Init, ImageNet 或 ImageNet++ 作為 Student Model 分別訓練。</p><p>另外被提到的是，在這樣的設置下，在 NoisyStudent 的 Loss Function 很難收斂，故引入了 Loss Normalization 的技巧。</p><p>原先在 Noisy Student 中，Loss Function 為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*F0xe77bi-w9l_FhG0xQrJg.png" /><figcaption>Loss Function in NoisyStudent</figcaption></figure><p>但在現行設置下，發現在 α 變動的狀況下，某些值會使訓練不穩定。故改為</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*hmv_kUqus7AF62UjGMjmJQ.png" /><figcaption>Adapted Loss Function</figcaption></figure><p>此外，我們有不同的 Tasks，且有不同的 Augmentation Strength 和 Data Size，所以這個 α 值得研究。故我們有下圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*CaYThh8CusxHxEQSvyHUjA.png" /><figcaption>α vs different settings</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*qOG_Y_PDUl6_7m-S-AbyHA.png" /><figcaption>Optimal α on different settings</figcaption></figure><p>上表揭示，當訓練步數增加，α 也應該要增加，越強力的 Augmentation ，α 則減少。</p><h3>Experiments</h3><h4>Pre-training hurts performance when stronger data augmentation is used</h4><p>下圖可以看出，<br>1. 當 Augmentation 越強力，Pre-training 越不如 Random Init<br>2. 當 Data Size 上升，Rand Init 與 Pre-training 的差距就越小<br>3. 越好的 Pre-trained Model，在小資料時有可能勝過 Random Init</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*llRYbPfUYLfWnwpQ28HChg.png" /><figcaption>Effects of Augmentation and Data Size on Pre-training</figcaption></figure><h4>The effected of augmentation and labeled dataset size on self-training</h4><p>說明一下下圖 Rand Init w/ ImageNet Self-training 的設置：<br>1. Teacher randomly initialize<br>2. Train on full COCO dataset <br>3. 完成訓練後（即第一行的 Rand Init），使用這個模型同時作為 Teacher 和 Student<br>4. Self-training on ImageNet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*NimoAtZnoKCi6JRx1UGU1w.png" /><figcaption>Effects of Augmentation and Data Size on Self-training</figcaption></figure><p>上表中，我們觀察到：<br>1. 使用 Pre-training 確實隨 Augmentation 強度增加而傷害模型<br>2. 在任何強度上，Self-training 皆打敗 Pre-training</p><h4>Self-training works across dataset sizes and is additive to pre-training</h4><p>再一次強調，這裡的 Self-training 開頭使用的模型是作為 Teacher 的 Pre-trained model 而非 Student，<strong>Student 皆是使用訓練完成的 Teacher 作為 Initialization。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*Ko2xYyTTRYGhKUFmhA2c9g.png" /><figcaption>Additive effect of Pre-training and Self-training</figcaption></figure><p>上表中可以觀察到，<br>1. 使用 Pre-training 確實隨使用的 Data Size 增加而表現較差<br>2. 較強的 Pre-trained model 確實會表現較好<br>3. 使用 Pre-training 後再使用 Self-training 也能夠加強準確度<br>4. 由於 Pre-training 會傷害模型，Rand Init w/ ImageNet Self-training 仍然表現最好<br><strong>5. 任何相同的狀況下，使用 Self-training 必然能夠有較好表現</strong></p><h4>Self-supervised pre-training also hurts when self-training helps in high data/strong augmentation regimes</h4><p>除了 Pre-training 外，作者對於 Self-Supervised 方法也很感興趣，因為它們與 Self-training 方法部份相似，能從非人類標籤資料擷取資訊，且如 SimCLR 已大致能達到與 Supervised Learning 相同的水準。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*Pb3MQuqez4JrapKlZQRrIQ.png" /><figcaption>Self-supervised vs Self-training</figcaption></figure><p>如上表，很顯然的，即便使用 SimCLR 方法，Pre-training 造成的傷害依然無法挽回。</p><p>這邊並沒有比較 low data regime 時的狀況，因為 Self-Supervised 顯然是需要使用大量資料訓練的方法。</p><h4>Exploring the limits of self-training and pre-training</h4><p>這一小節嘗試使用目前非常強力的兩個架構 SpineNet on COCO and NAS-FPN with EfficientNet-L2 on PASCAL，將 Self-training 推向極限。</p><p>在 COCO 的實驗中，由於前述實驗結果認為，使用 full COCO dataset 時，Pre-training 會傷害模型效果，故在此不使用。</p><p>從 EfficientNet-D7 轉為使用大型三倍以上的 SpineNet-190 ，Self-training 依然有驚人效果，顯示 Self-training 有適用在不同任務、不同尺度模型上的潛力。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*rHaic4e8XmpzPDclKqByTA.png" /><figcaption>COCO SOTA with Self-training</figcaption></figure><p>而在 PASCAL VOL 2012 的資料集中，由於它是相對較小的資料集，故以下實驗使用 Pre-training 。</p><p>雖然 Backbone 仍是使用 EfficientNet 系列，但其 task head 則是使用複雜的（有點畸形的） NAS-FPN，仍有很好的效果，顯示 Self-training 對於不同任務的適應性。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*nPIYar4AibcAPGsPqoPAng.png" /><figcaption>PASCAL SOTA with Self-training</figcaption></figure><h3>Discussion</h3><h4>Rethinking pre-training and universal feature representations</h4><p>Pre-training 的糟糕表現直覺上似乎很合理（只是很少有系統的被討論）。我們希望透過在大型資料集如 ImageNet 上的成功訓練，讓它能夠幫助其他目標資料集的訓練，當目標資料集很小時，Pre-training 仍然可以從原本的資料集找到能夠幫助目標資料集的特徵，但是當目標資料集逐漸成長（或是加入更強力的 Augmentation），可能兩個資料集的有效特徵就會不同，甚至衝突了。</p><blockquote>Such adaptation is often needed when switching tasks because, for example, good features for ImageNet may discard positional information which is needed for COCO.</blockquote><h4>The benefit of joint-training</h4><p>所以為什麼 Self-training 表現如此之好？還不確定，但我們可以觀察到的是，除了使用 Supervised 的方法外，還加入了 pseudo label，在 J<strong><em>oint-training</em></strong> 下，這樣的 <strong><em>mismatch </em></strong>可能導致效果。</p><p>換句話說，Self-training 是不同演算法的 Joint-training。</p><blockquote>A strength of the self-training paradigm is that it jointly trains the supervised and self-training objectives, thereby addressing the mismatch between them.</blockquote><p>那我們可以在其他什麼地方得到 mismatch 並 Joint-training 呢？</p><p>這邊展示了不同任務的 Joint-training，同時使用 COCO 和 ImageNet，也就是在訓練 Teacher 時，Randomly Initialize 並使用 COCO 和 ImageNet 訓練。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*g2iffX7rLaqiO7HTBBqFYg.png" /><figcaption>Supervised and Self-training and Joint-training</figcaption></figure><p>這裡並沒有詳細的 Joint-training 的細節，但我猜測應該是同時使用兩個 task head 並計算 total loss。</p><p>不過這裡有一點非常奇怪，在 COCO Sup. Training 中，33.3 &gt; 30.7？Pre-training 應該要略遜於 Rand Init 吧？</p><p>沒錯，比對前面的準確度表格，這是僅使用 20% COCO training set 的準確度，所以結論才會是 <strong>同時使用 Pre-training + Self-training + Joint-training 效果最佳</strong>，請注意這是在<strong>僅使用小資料的狀況</strong>下，使用 100% COCO 時，Joint-training 的效果，並沒有被確認。</p><h4>The importance of task alignment</h4><p>什麼可能導致 Pre-training 的效果不如理想？</p><p>在 PASCAL 上，使用了 training + val 的 Pre-trained，即便多了人類標注的 val ，反而比僅使用 training set 的 Pre-trained 更糟，這是因為 val 的資料非常的雜亂，使其使用 val 的特徵後，反而更無法幫助日後的訓練。</p><p>另外，在 <a href="https://openaccess.thecvf.com/content_ICCV_2019/papers/Shao_Objects365_A_Large-Scale_High-Quality_Dataset_for_Object_Detection_ICCV_2019_paper.pdf">Objects365:A large-scale, high-quality dataset for object detection</a> 中，使用了 Pre-train on OpenImages，並 fine-tune on COCO，即便兩者都有 annotated bounding box ，比起 train-from-scratch on COCO 效果更糟。</p><p>這裡暗示了，Self-training 因為是自行標記，而非使用來自不同處的人類標籤，達到了 task alignment 的效果，這對於 task adaption 是非常重要的。</p><h4>Limitations</h4><p>但 Self-training 是有代價的：</p><blockquote>The speedup thanks to pre-training ranges from 1.3x to 8x depending on the pre-trained model quality, strength of data augmentation, and dataset size.</blockquote><p>就是訓練時間相較 Pre-training 非常的久。所以如果時間緊迫，或是受限於 computing power，Pre-training 依然是最佳解。</p><h4>The scalability, generality and flexibility of self-training</h4><p>Self-training 除了能夠達到 SOTA 以外，也具有另外非常多的優勢：</p><ol><li>Scalability<br>除了在非常肥大模型上也能夠達到更好的效果外，在非常巨量的資料集底下，也能夠有效的使用其資訊。</li><li>Flexibility<br>在任何量級的資料集、任何任務、任何架構都能夠使用。Scalability 保證了持續向上進步的空間，Flexibility 則討論了其廣度。</li><li>Generality<br>在 Noisy Student 中，我們知道了 Self-training 非常重要的一點是其表現的提昇，來自於能夠適應非常高強度的噪聲。故其比起 Pre-training 能夠適應更多的模式，甚至我們能夠合理地想像它在 Adversarial Training 也會有很好的效果。</li></ol><h3>Conclusion and Notes</h3><p>本文雖然是大吹特吹 Self-training ，但很重要的是很清楚的指出 Pre-training 的極限，在怎麼樣的場景下應該使用何者。</p><p>但我認為有一件事情未被解決：</p><p>文中使用了 20% COCO 作為 low data regime，此時 Pre-training 表現最好，準確度隨後遞減。</p><p><strong>而在現實應用中，我們如何知道自己手中的資料集屬於 low data regime 呢？</strong></p><p>最簡單的方法是透過實驗，計算 Pre-trained model 使用的資料量和 fine-tune 使用的資料量，不過顯然很粗糙，畢竟我們有不同的任務，不同資料集的特性也不同。</p><p>我認為，<strong>應該找出量化資訊量的方法</strong>，譬如 Pre-trained model 對於 target tasks 有效的資訊量，以及 target data 需要達到什麼數量才能增加 Pre-trained model 的資訊量等等，這樣結論會更精準。</p><p>-</p><p>另外，在這總結一下 Pre-training 與 Self-training 各自應用場景的不同：</p><h4>使用 Pre-training 的時機</h4><ol><li>僅有小部份 labeled data 或 labeled data 難以取得時</li><li>有訓練時間的壓力時</li><li>在應用場景穩定，不需要對抗噪聲時</li></ol><p>有任一場景，就是使用 Pre-training 的好時機。</p><h4>使用 Self-training 的時機</h4><ol><li>追求最好的準確度、更好的泛化能力</li><li>能夠有很長的訓練時間，或大量的計算能力時</li><li>有非常多的 unlabeled data 時</li></ol><p>我認為要以上三項都要大致滿足，才應該使用 Self-training。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=737afae25317" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-rethinking-pre-training-and-self-training-series-2-of-3-737afae25317">Review: Rethinking Pre-training and Self-training — Series 2 of 3</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review: Self-training with Noisy Student improves ImageNet classification — Series 1 of 3]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/paper-review-self-training-with-noisy-student-improves-imagenet-classification-series-1-of-3-2f0be0918294?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f0be0918294</guid>
            <category><![CDATA[semi-supervised-learning]]></category>
            <category><![CDATA[efficientnet]]></category>
            <category><![CDATA[noisystudent]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 09:24:07 GMT</pubDate>
            <atom:updated>2021-02-27T12:12:30.591Z</atom:updated>
            <content:encoded><![CDATA[<h3>Review: Self-training with Noisy Student improves ImageNet classification — Series 1 of 3</h3><p><a href="https://arxiv.org/abs/1911.04252">Self-training with Noisy Student improves ImageNet classification</a></p><p>這篇是出自 Google 的 Self-training 系列第一篇，和 <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-a-series-of-semi-supervised-learning-algorithms-mixmatch-remixmatch-and-fixmatch-354e83cc8b5b">FixMatch</a> 系列和 <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-a-series-of-semi-supervised-learning-algorithms-mixmatch-remixmatch-and-fixmatch-354e83cc8b5b">SimCLR</a> 不同，這兩者相較之下都使用較小，或一部分的資料作為 Training Set，這系列的思想是用最大的資料集 + 最多的運算機器 + 最強的演算法挑戰 ImageNet SOTA。</p><p>接下來的兩篇分別會是<br>1. Rethinking Pre-training and Self-training<br>2. Meta Pseudo Labels</p><p>而 Meta Pseudo Labels 在近日成為新的 ImageNet SOTA，在了解它之前，讓我們先來看看它的前身，也就是這篇 Noisy Student。</p><h3>Introduction</h3><p>首先，這篇的初衷使它與眾不同：</p><blockquote>By showing the models only labeled images, we limit ourselves from making use of unlabeled images available in much larger quantities to improve accuracy and robustness of SOTA models.</blockquote><p>作為 Skynet 的可能候選人，<a href="https://www.quora.com/How-much-data-does-Google-have">Google 無疑是坐擁地球上最多資料的巨頭之一</a>，該如何有效使用 unlabeled data 成了大問題，請工讀生來標記是一個選項，但 Google 也擁有最多的 TPU 以及強大的 EfficientNet，所以…</p><p>請 EfficientNet 來標記看看如何？也就是 teacher-student framework。</p><p><strong>我個人認為</strong>這來自於三個直覺 :<br>1. 模型標注的比人快、更省成本<br>2. 對於非 ImageNet 的資料，人類很難準確分類到 ImageNet<br>3. 出自於模型的標記(猜測)，也許對於另一個模型更能夠理解</p><p>有些批評(註一)認為引入大量額外且未公開的JFT300 資料，成為 ImageNet SOTA 似乎沒什麼好說嘴的，因為非常符合直覺(但有時實現直覺也很困難)。但本文應該關注的價值是如何<strong>有效率</strong>的應用多而無用的 unlabeled data，更關注於資料層面，而不該以演算法眼光看待。</p><h3>Noisy Student Training</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*-a6g3lxh7ORFTYoIegi2sg.png" /><figcaption>Noisy Student Algorithm</figcaption></figure><p>演算法相當簡單，由一個事先訓練好的 Teacher Model 將 unlabeled data 標記後，和 labeled data 一起交給 Student Model 訓練。在 Student Model 表現超越 Teacher Model 後，將該 Student Model 作為老師訓練新學生，如此循序。</p><p>這種 teacher-student framework 並非本文首創，本文重點實際上是 <em>Adding Noise </em>:</p><blockquote>In typical self-training with the teacher-student framework, noise injection to the student is not used by default, or the role of noise is not fully understood or justified.</blockquote><p>而本文應用了三種 Noise，即 <br>1. RandAugment (input noise)，僅應用在 input to student model<br>2. Dropout (model noise) for both models<br>3. Stochastic depth (model noise) (註二) for both models</p><p>RandAugment 不多作解釋，有意思的是後兩者。作者認為 dropout 及 stochastic depth 有助於 teacher model<strong> </strong>形成 emsemble model，而不是以 regularization 的觀點理解。</p><blockquote>when dropout and stochastic depth function are used as noise, the teacher behaves like an ensemble at inference time (when it generates pseudo labels), whereas the student behaves like a single model. <strong>In other words, the student is forced to mimic a more powerful ensemble model.</strong></blockquote><p>有點小疑惑的是，在 <a href="https://github.com/google-research/noisystudent">source code</a> 中，teacher 和 student <a href="https://github.com/google-research/noisystudent/blob/c5ae6524c6ba37d3cd133107c21250c4b8fb7a28/main.py#L423">帶有相同的 dropout </a>，故這邊指的 <strong><em>student behaves like a single model</em></strong> 並不是沒有使用 dropout 的意思。</p><p>此外，data filtering 和 data balancing 以及 soft pseudo labels 能達到較好的效果，至 ablation study 時再詳細說明。</p><h3>Experiments</h3><p>這個小節主要談論一些實驗細節：</p><ol><li>使用公開資料集 YFCC100M 與 JFT300 結果比較，YFCC 可替代 JFT 。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*rRhV2F_9wOWRc9P8pcjUaQ.png" /><figcaption>YFCC vs JFT</figcaption></figure><p>2. 僅使用 Teacher Model Confi. &gt; 0.3 的 unlabeled data ，即Data Filter，從 JFT 挑出 81M。並平衡 unlabeled data 的分類，重複挑選數量不達到 130K 的圖片，使其達到 130K，使 unlabeled data 總數從 81M 成長到 130M。</p><p>3. 使用 EfficientNet-B7 和 EfficientNet-L2，後者訓練時間是前者的 5 倍，且使用 2048 cores TPU 需要六天時間。</p><blockquote>EfficientNet-L2, needs to be trained for 6 days on a Cloud TPU v3 Pod, which has 2048 cores, if the unlabeled batch size is 14x the labeled batch size.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*7ym9nkAA_sC_evCQP2HQVA.png" /><figcaption>EfficientNet-B7 and EfficientNet-L2 Details</figcaption></figure><p>4. Iterative training<br>先使用 EfficientNet-B7 作為老師，EfficientNet-L2 作為學生，並迭代。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*Hiu0a37wknl93J__pXxpFw.png" /><figcaption>Iterative training</figcaption></figure><p>5. ImageNet Results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRVkaBxsPW5aRyWTOVckRA.png" /><figcaption>Final Result</figcaption></figure><p>6. Robustness Results on ImageNet-A, ImageNet-C and ImageNet-P (註三)<br>除了 Accuracy 提昇，Robustness 也是一大亮點。</p><p>ImageNet-A 主要由 ImageNet 中較困難的圖片組成，ImageNet-C 和 ImageNet-P 主要測試模型對於 Corruptions 的抵抗力。</p><p>ImageNet-A 達到 Top1 <strong>83.7%</strong> (ResNet50 <strong>0%</strong>, EfficientNet-L2 <strong>49.6%</strong>)<br>ImageNet-C 達到 Top1 <strong>77.8% </strong>(EfficientNet-L2 <strong>66.6%</strong>)<br>ImageNet-P 達到 Top1 <strong>86.4% </strong>(EfficientNet-L2 <strong>81.6%</strong>)<br>詳細數據請見原文 Table 3, Table 4, Table 5。</p><p>以下是 Noisy Student(黑色字體) 和 supervised EfficientNet-L2 (紅色字體)在三個資料集的比較。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBDCl2QgH9JuqSz911JUzQ.png" /><figcaption>ImageNet-A, C, P and EfficientNet Predicitons</figcaption></figure><p>另外，使用 FGSM attack，也就是在 gradient descent update 時，對每一個 pixel 的 gradient 都直接加上一個定值 epsilon，算是很殘忍的攻擊，但 Noisy Student 仍有非常強的抵抗力。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*WV-PGns-aRCptYSRY6Pa9w.png" /><figcaption>Accuracy on FGSM</figcaption></figure><h3>Ablation Study</h3><ol><li>The Importance of Noise in Self-training</li></ol><p>先前提過，teacher-student framework 並非本文重點，而是 adding noise。由於學生是由老師的 pseudo labels 學習，當學生預測出的 labels 等於 pseudo labels ，CE loss 理當會為零</p><p>所以如果學生要超越老師，完美學習老師的答案也是不夠的，故 noise 勢必要扮演重要角色。</p><p>故在此，我們逐漸移除 RandAugment 和 dropout 以及 stochastic depth，再觀察訓練成效，如果前後存在差異，該差異就是這三種 noise 帶來的效益。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*anKQwB3UorbCiv1tpV6IaA.png" /><figcaption>Ablation for noise</figcaption></figure><p>則 83.9% - 83.2% = 0.7 % 以及 85.1% - 84.3% = 0.8% 為 adding noise boost。</p><p>這裡有三個小細節：</p><p>(a) 在 noisy student w/o Aug, SD, Dropout 時，130M 的資料中，仍使 B5 從 84% 小幅提昇 84.3% ，作者把這歸咎於 SGD 的隨機性。</p><p>(b) 雖然沒有 iterative training ，但這提昇仍然較小(85.1% - 84%=1.1%)。原因可能是因為為了節省訓練時間，這裡使 labeled data : unlabeled data = 1: 1 而非 1:14 or 1:28。(Finding #7)</p><p>(c) 在 noisy student 的第三種狀況 teacher w. Aug, SD, Dropout ，source code 當中 teacher 原本就有使用 SD 和 Dropout 了，架構與 Student 一模一樣，考量到 Dropout 無法在訓練時使用而 Inference 時不使用，這應該是合理的，<strong>故 84.4% 與 85.1% 的差距應該僅是有無在 input image of teacher image 使用 Aug 而已。</strong></p><p>2. Additional Ablation Study Summarization<br>共有七項實驗，這邊挑出比較特別的一項討論</p><blockquote>Finding #8: Training the student from scratch is sometimes better than initializing the student with the teacher and the student initialized with the teacher still requires a large number of training epochs to perform well.</blockquote><p>Finding #8 主要是討論在使用 Noisy Student 前，是否應該讓 teacher model 使用 unlabeled data ，讓 student model 訓練一段時間。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*cOqDyYC2Z5hECtS8nKfaZA.png" /><figcaption>Warm-starting the Student Model</figcaption></figure><p><strong>答案是否定的，應該直接進行 Noisy Student。<br></strong>除了這樣的方式花費的時間和 Noisy Student 幾無二致之外，甚至有可能會使 student model 收斂在 local minimum：</p><blockquote>For example, when we use EfficientNet-B7 with an accuracy of 86.4% as the teacher, the student model initialized with the teacher achieves an accuracy of 86.4% halfway through the training but gets stuck there when trained for 210 epochs, …</blockquote><p>其他六項實驗都不錯，但大多前述有提及，礙於篇幅，詳細部份還是推薦各位至原文欣賞。</p><h3><strong>Conlusion</strong></h3><blockquote>We found that self-training is a simple and effective algorithm to leverage unlabeled data <strong>at scale</strong>. We improved it by adding noise to the student, hence the name Noisy Student Training, to learn beyond the teacher’s knowledge</blockquote><p>Noisy Student 的確是佳作，將 teacher-student framework 稍加改良就得到相當好的成效，維持簡潔優美的演算法。但問題是，它的應用場景是很難得的，先不說不斷迭代訓練模型，提昇 1% - 5% 是不是符合成本，它所需的資料量和運算能力也不是凡人所能想像的。</p><p>雖是如此，除去本文的場景，我認為它還能有許多符合凡人想像的應用，譬如用於 model compression 、model capacity research、adversarial training 等。</p><p>下一篇我們將談談由 Kaiming He 何恺明的 <a href="https://arxiv.org/abs/1811.08883">Rethinking imagenet pre-training </a>所啟發的 Rethinking Pre-training and Self-training。我們已知 ImageNet pre-training 並不一定能幫助訓練了，那 Self-training 能夠取代 pre-training 嗎？下回待續。</p><h3>Reference</h3><p>[1] <a href="https://github.com/google-research/noisystudent">Source Code of Noisy Student</a>, credits to Google Research</p><h4>Note</h4><p>註一：<a href="https://www.reddit.com/r/MachineLearning/comments/dvh8e8/191104252_selftraining_with_noisy_student/f7fl9je?utm_source=share&amp;utm_medium=web2x&amp;context=3">reddit</a> ，或是對 Meta Pseudo Labels <a href="https://zhuanlan.zhihu.com/p/345416401">知乎</a></p><p>註二：Stochastic depth 中文理解為「隨機深度」，出自於 <a href="https://arxiv.org/abs/1603.09382v1?utm_content=bufferbf6d7&amp;utm_medium=social&amp;utm_source=twitter.com&amp;utm_campaign=buffer">Deep Networks with Stochastic Depth</a>，用於 ResNet 當中：產生 Random Binomial Variable (1 or 0)，乘以殘差部份，意即隨機加上殘差。</p><p>註三：ImageNet-A 是 ResNet50 無法準確分類的, ImageNet-C 和 ImageNet-P 都是帶有 Corruption 的圖片。詳細參考 <a href="https://kushajveersingh.github.io/blog/discussion/2020/08/31/post-0012.html#How-ImageNet-A-is-constructed?">ImageNet Dataset Advancements</a>。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f0be0918294" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/paper-review-self-training-with-noisy-student-improves-imagenet-classification-series-1-of-3-2f0be0918294">Review: Self-training with Noisy Student improves ImageNet classification — Series 1 of 3</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does Batch Normalization REALLY Work?(It's not about Internal Variate Shift)]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/how-does-batch-normalization-really-work-its-not-about-internal-variate-shift-a0205a49faff?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0205a49faff</guid>
            <category><![CDATA[batch-normalization]]></category>
            <category><![CDATA[l2-regularization]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[l1-regularization]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Mon, 16 Nov 2020 08:29:08 GMT</pubDate>
            <atom:updated>2020-11-16T08:34:44.732Z</atom:updated>
            <content:encoded><![CDATA[<p>自 Batch Normalization 在 2014 被發明，在 Deep Learning 的領域中就隨處可見，雖其後偶有變化如 Group Normalization 等，但其地位仍舉足輕重，因為實驗表明，它能夠</p><ol><li>加速訓練速度，讓 Neural Network 更快收斂</li><li>附帶 Regularization，讓 Neural Network 更加 Generalized</li></ol><p>針對第一點，Ian Goodfellow 甚至說過</p><blockquote><em>Before BN, we thought that it was almost impossible to efficiently train deep models using sigmoid in the hidden layers. We considered several approaches to tackle training instability, such as looking for better initialization methods. Those pieces of solution were heavily heuristic, and way too fragile to be satisfactory. </em><strong><em>Batch Normalization makes those unstable networks trainable </em></strong><em>; that’s what this example shows.(</em><a href="https://www.youtube.com/watch?v=Xogn6veSyxA"><em>source</em></a><em>)</em></blockquote><p>然而，Batch Normalization 如何使得不穩定的訓練變得穩定，仍然成謎。</p><h3>Internal Covariate Shift</h3><p>當然，我們都知道官方說法是 BN 能夠有效減少 “Internal Covariate Shift”，而對於越深層的網絡，這種擾動所造成的蝴蝶效應尤其明顯。</p><p>聽起來好像很有道理，但有幾個疑問：</p><h4>1. Internal Covariate Shift 到底是什麼</h4><p>在原始論文中，是這樣描述 ICS 的</p><blockquote>We define <strong>Internal Covariate Shift</strong> as <strong>the change in the distribution of network activations</strong> due to the change in network parameters during training. To improve the training, we seek to reduce the internal covariate shift.</blockquote><p>但怎麼樣的 “change” 才是 ICS？我們還有下圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*I3BxPJZ_8qMdcf1F7nTroQ.png" /><figcaption>The impacts of Batch Normalization</figcaption></figure><p>(b)(c) 是將 layer input 輸入到 sigmoid 後，將 quantile 15, 50, 85 分別依 training step 畫下。可見 (b) 更不穩定，即表現更大的 ICS，加了 BN 的 (c) 則有更小的 ICS。</p><p>事實上，這樣的定義還是很模糊。為什麼只是 quantile 15, 50, 85？不同的資料集會有不同的 quantile 分佈應該是很直覺的事情，這樣的量化依然有意義嗎？</p><p>再來，上圖的確展現了明顯的不同，但是當比較都很平滑的兩個分佈，我們要如何評量哪個帶有更大的 ICS ？</p><h4>2. Batch Normalization can reduce internal covariate shift？</h4><p>接續上文，最廣為人知的 ICS 定義是</p><blockquote>Informally, ICS refers to the change in the distribution of layer inputs caused by updates to the preceding layers.</blockquote><blockquote>-<em> </em><strong>How Does Batch Normalization Help Optimization? (2018, Shibani Santurkar et al.)</strong></blockquote><p>在原始論文中的 Fig.1 卻不是依照這樣的定義設計實驗的。它事實上僅有討論各層中 quantile 15, 50, 85 的值，和該層「分布」實在相差甚遠。</p><p>我們需要從非正式定義中，定義一個正式的 ICS 定義，並檢視 BN 是否真的減少了 ICS。</p><h4><strong>3. 更小的 ICS = 更穩定的訓練？</strong></h4><p>我們暫且擱置上文談到不正式的 ICS 定義，甚至 BN 是不是真的能減少 ICS 也不說，實驗本身的邏輯也是有疑慮的。BN 能夠使訓練更穩定，也能夠使模型有更小的 ICS，<strong>但這並不代表，更小的 ICS 會有更穩定的訓練</strong>。</p><p>我們可以設計實驗是：<br>一、不使用 BN，直接干預 ICS，使得 ICS 與穩定訓練有直接因果。<br>或是<br>二、使用 BN，直接干預 ICS ，使得更大的 ICS 仍能<strong>穩定訓練</strong>(註一)。</p><p>這樣我們就能夠證明，ICS 確實是訓練不穩定的來源，或是 ICS 與不穩定的訓練毫無關係。</p><h3>How Does Batch Normalization Help Optimization?</h3><p>對於 BN 與 ICS 對訓練的關係有太多需要釐清，這篇論文除了點出並解決上述三個疑問外，也針對 BN 的運作之謎提出另一個假說。</p><h4>1. Does BatchNorm’s performance stem from controlling internal covariate shift?</h4><p>在 CIFAR-10 上設計一個實驗，分別比較</p><p>a. 無 BN 的 Standard VGG<br>b. 有 BN 的 Standard VGG<br>c. 有 BN 的 Standard VGG ，且在 每個 BN 後加上一層 Random Noise ，表現出無法被學習的 Internal Variate Shift</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*GMBvQxx5AtD0of7fEtykMQ.png" /><figcaption>Adding ICS manually after BN</figcaption></figure><p>可以看到，Standard + BN 與 Standard + Noisy BN 在左圖的訓練表現中幾乎毫無差異。但是右圖中，尤其在 Layer #13 ，前後 step 所表現的 distribution of activations 有明顯差異，也就是帶有很大的 ICS。</p><p>附錄中我們可以得到另一張圖，闡述 ICS 並不會導致不穩定的訓練</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*zwNBEDyfdvpLEJ3RpKq4YQ.png" /><figcaption>ICS between BNsetting</figcaption></figure><p>故，我們一直以來認為的，降低 Internal Covariate Shift 能夠穩定訓練是有問題的。</p><h4>2. Is BatchNorm reducing internal covariate shift?</h4><p>我們重新定義 Internal Covariate Shift，並將它稍微改寫，從網絡輸入的分佈改變，聚焦在 Gradient 上，畢竟，我們最終想討論的是訓練表現，而此訓練為 gradient descent-based training algorithms。</p><blockquote>Is there a broader notion of <strong>internal covariate shift</strong> that has such a direct link to training performance? And if so, does BatchNorm indeed reduce this notion? […] To answer this question, we consider a broader notion of <strong>internal covariate shift</strong> that is more tied to the underlying optimization task. (After all the success of BatchNorm is largely of an optimization nature.)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*ul6N0b7nDeEgU9a0gfWHxg.png" /><figcaption>Formal Definition of Internal Covariate Shift</figcaption></figure><p>讓 ICS 為 i-th Layer 前的權重變化前後，Gradient of i-th Layer 的差值。</p><blockquote>The difference between G and G0 thus reflects the change in the optimization landscape of Wi caused by the changes to its input. It thus captures precisely the effect of cross-layer dependencies that could be problematic for training.</blockquote><p>使用這個定義，我們比較 Standard VGG 和 Standard VGG with BN，得到</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*wtRnQqPa5-oAB5sVI0k5Wg.png" /><figcaption>BN effect on New ICS</figcaption></figure><p>上圖顯示，BN 在新定義的 ICS 上仍沒有效果，不但不會減少，甚至會增加 ICS。</p><p>自此，Internal Coariate Shift 假說已經全數告破。</p><h4>3. Why does BatchNorm work?</h4><p>既然如此，為什麼 BN 能夠穩定訓練？</p><p>本文提出另一個假說 : <strong>The smoothing effect of BatchNorm</strong></p><blockquote>Indeed, we identify the key impact that BatchNorm has on the training process: it reparametrizes the underlying optimization problem to make its landscape significantly more smooth.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*59a2dazvo3hGiqwxI6fiYw.png" /><figcaption>Measurements of Smoothness</figcaption></figure><p>上圖 (a) 為 gradient of the loss at i-th step during training，(b) 為 difference of gradient of the loss between 2 steps。可以見到使用了 BN 的訓練在每一步都有十分穩定的 gradient ，換句話說，網絡權重的更新非常穩定，並不會突然的劇烈改變，直覺上，這代表我們有更平滑的 loss landscape。</p><p>對於 (c)，本文提出了兩項指標用以量化 loss function 的平滑程度。</p><p>a. Lipschitzness<br>一個函數的 Lipschitzness 越好，表示它僅能夠在一個更小的範圍內變化，參考下圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*T2Qa8PwSN7clt966N2-K_w.png" /><figcaption>Lipschitz Continuity</figcaption></figure><p>上圖兩條綠線在該函數上的交叉點稱為 x，而 f(x + ε) 只允許存在於綠色的範圍中。如果出現在白色區域中，表示函數的變化很大，我們會說該函數的 Lipschitzness 很差。滿足該性質的函數，我們又稱其為 L-Lipschitz 的。即存在一常數 L 使得：</p><p><strong><em>f is L-Lipschitz if |f(x) − f(x + ε)| ≤ L|ε|, for all ε.</em></strong></p><p>b. β-smoothness<br>將 Lipschitzness 應用至 gradient ，得到另一更嚴格的數值 β-smoothness，即</p><p><strong><em>|Grad(Loss_i) − Grad(Loss_i+1)| ＝ β|Loss_i-Loss_i+1|</em></strong></p><p>將每一步訓練的 β 畫出，得到上圖 Fig. 4(c)</p><h4>4. Is BatchNorm the best (only?) way to smoothen the landscape?</h4><p>最後，作者發現使用 L-norm 也可以得到類似於 Batch Normalization 的效果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*qap7z6FeQhpaOCuBA851rA.png" /><figcaption>Comparisons between L-norm and BN</figcaption></figure><p>即便各層仍保有相較 BN 更大的 Covariate Shift：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*6RGZ-ZedX42BORf53WBoqA.png" /><figcaption>Covariate Shift of L-norm</figcaption></figure><h3>Reference</h3><p>[1] How Does Batch Normalization Help Optimization? <a href="https://arxiv.org/abs/1805.11604"><br>arXiv:1805.11604</a> (2018)</p><p>[2] <a href="https://towardsdatascience.com/batch-normalization-in-3-levels-of-understanding-14c2da90a338#fb36">Batch normalization in 3 levels of understanding</a>, credits to <a href="https://medium.com/@jtkarl"><strong>Johann Huber</strong></a></p><p>[3] <a href="https://zhuanlan.zhihu.com/p/64312433">How Does Batch Normalization Help Optimization? 知乎</a>, credits to <a href="https://www.zhihu.com/people/zhao-yong-sen-43">seniusen</a></p><p>註一: <strong>穩定訓練</strong>指的是模型更快的收斂，以及訓練過程中 Loss 相對平滑的下降，即使用 BN 所帶來的效果。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0205a49faff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/how-does-batch-normalization-really-work-its-not-about-internal-variate-shift-a0205a49faff">How does Batch Normalization REALLY Work?(It&#39;s not about Internal Variate Shift)</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review: Attention is all you need]]></title>
            <link>https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-attention-is-all-you-need-62a1c93c48a5?source=rss-e547cb7eedb0------2</link>
            <guid isPermaLink="false">https://medium.com/p/62a1c93c48a5</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[self-attention]]></category>
            <category><![CDATA[attention-is-all-you-need]]></category>
            <category><![CDATA[rnn]]></category>
            <dc:creator><![CDATA[Guan]]></dc:creator>
            <pubDate>Fri, 09 Oct 2020 04:47:21 GMT</pubDate>
            <atom:updated>2020-10-10T14:27:12.229Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a></p><p>作為 Transformer 的濫觴，2017 年發表時，其轟動大概能相較於 CV 中的 ResNet。今日來看，Transformer 似乎有過之而無不及，其隨後的 Bert 和 GPT 等大大開拓了人們對於 Sequence Tasks 的想像，現代的 NLP 大概很難不提到 Transformer ，所以今天就從 Transformer 源頭之一 — Attention is all you need 講起吧。</p><h3>Introduction</h3><p>在 Transformer 前的 LSTM-based 模型最致命的弱點是無法進行平行運算，由於 t 時刻的狀態是 t-1 時刻的函數，LSTM 天生就是 Sequential Computing ，難以進行平行化，使得使用大型 LSTM 模型、大 batch size 或長序列的訓練任務上，訓練的時間令人難以接受。</p><p>除此之外，Transformer 和 LSTM-based 的模型相較起來，輸入和輸出序列中前後的距離對於後者非常重要，越遙遠的 element 之間越難被 LSTM 連結，而前者的 Attention 機制正是要盡可能地將 global dependencies 學習起來，在輸入與輸出的關鍵字的位置距離十分遙遠時也有好的表現。</p><p>這兩點在後面的章節會有詳細的解說。</p><p>另外，在提出 Attention Model 的前作 <a href="https://arxiv.org/pdf/1409.0473.pdf">NEURAL MACHINE TRANSLATION BY JOINTLY LEARNING TO ALIGN AND TRANSLATE</a> 點明了 RNN Encoder-Decoder (<a href="https://arxiv.org/abs/1406.1078">Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation</a>) 中架構的不足，其 hidden layer 對於單一 sequence 輸入僅有單一固定長度的 context vector ，而 Attention 則會對 sequence 中每一 token 都產生 context vector，使資訊更能夠被 Encoder 保留，本篇自然也承襲這樣的優點。</p><h3>Model Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*6UnhXuD0hFzt7YBu1ONrcQ.png" /><figcaption>Model Architecture</figcaption></figure><p>Transformer 由 Encoder 及 Decoder 組成，兩者的性質迥異，應該分開理解。前者用於壓縮序列資訊，後者則用於將前者抽取的資訊轉換（解壓縮）為任務所需要的資訊。</p><p>一個 Encoder Layer 主要有下列操作：</p><h4>Muti-Head Attention</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*1AQLecxGvtjoKWBxLWj7PQ.png" /><figcaption>Scaled Dot-Product and Multi-Head</figcaption></figure><p>輸入一個矩陣有 shape 即 (batch_size, seq_len, num_feature)，為方便說明假設為 (8, 64, 512) 。</p><p>先將輸入矩陣乘以 n_head 個 W^Q, W^K, W^V ，其 shape 為 (8, 512, 512 / n_head )，故得到有 n_head 個 Q, K, V ，每一個 shape 皆為 (8, 64, 512 / n_head)。</p><p>其中 Q 及 K 先行相乘，得到 n_head 個矩陣為 shape (8, 64, 64)，再進行 element-wise scale 及 softmax，shape 不變。</p><p>最後和 V (8, 64, 512 / n_head) 相乘，得到 n_head 個輸出矩陣 (8, 64, 512 / n_head)，最終將其 concatenate ，得到最終輸出 (8, 64, 512)，與輸入矩陣 shape 相同。就算 shape 不同，也可以再乘以 W^O 做 upsampling or downsampling。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*9FQHaDk0QM1hBuFMgrdOyw.png" /><figcaption>Details of Multi-Head Attention</figcaption></figure><h4>Padding Mask</h4><p>在 NLP 當中的常用 Mask，用於 mini-batch 當中，帶有不同長度的 sequence 的時候，譬如說十句不同長短的句子。通常做 zero-padding。</p><h4>Add (residual connection) and LayerNorm</h4><p>由於輸入與輸出擁有相同的 shape ，我們可以使用 residual connection 將輸出加上輸入。並使用 LayerNorm 在每一個 instance 的方向上進行 normalization。</p><p>有趣的是，有不少論文探討 LayerNorm 在 Transfomer 架構中的影響，如 <a href="https://arxiv.org/abs/2002.04745">On Layer Normalization in the Transformer Architecture</a> 討論了此架構對訓練時 Gradient ，以及Pre-layernorm (norm before residual)和 Post-layernorm (本文架構) 對 warm-up 與否訓練時的影響，並指明前者不需要 warm-up，且效果更好。</p><h4>FeedForward</h4><p>對每個 position 的 embedding 進行操作，假設輸入為 (8, 64, 512) ，以 ( 512, 2024) 全連接層相乘，得到輸出 (8, 64, 2024) ，進行 relu 運算，再與 (2024, 512) 全連接層相乘，得到輸出 (8, 64, 51參見[編輯]2)。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*icFroIL--DxEfLLjE3nXLg.png" /><figcaption>FeedForward</figcaption></figure><h4>Position Encoding</h4><p>在 Encoder-Decoder 操作中不存在 Convolution 或 Recurrence ，只有dot-product，前者能夠使用矩陣的 spatial information ，後者則是 order of sequence 的訊息，如果將輸入矩陣沿著維度 1 做 random shuffle，得到的 Attention 結果會是一樣的。所以我們需要 “inject” 資訊到輸入的矩陣中，使訊息直接被儲存在 embedding vector 的值當中。即：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*3GCAQzZblm9TsQF3z6oCUg.png" /><figcaption>sinusoid</figcaption></figure><p><em>pos</em> 為在該元素在序列中的位置，偶數位使用 sine 而奇數位使用 cosine。<em>i </em>則為在維度中的 index 。假設一輸入序列有 shape (1, 64, 512) ，矩陣中在 (1, 32, 120) 的值會被加上 sin(32 / 10000^(240/512)) = 0.41389…</p><p>之所以使用這樣的形式使因為正餘弦在 k steps 以外會擁有相同的值，及 PE_pos = PE_(pos + k)，作者認為這種形式會使模型更容易理解 position encoding，也確實某種程度符合我們對序列資料建模的認知。</p><p>以上為 Encoder Layer 的操作，Decoder Layer 有著幾乎一樣的操作，除了 Scaled Dot-Product 中 Mask 的部份。</p><h4>Sequence Mask</h4><p>也是在 NLP 當中的常用 Mask。在 Scaled Dot-Product 中，Decoder 在 scaled 後必須還要經過 mask 操作，這樣的用意是，序列中第 i 個元素的，僅能仰賴 i-th 以前的資訊做預測，不讓 Decoder 看見未來的訊息，所以我們必須將包含 i + 1 之後的 vectors 掩蓋起來。</p><p>假設我們有序列 [1, 2, 3, 4] ，故 scale 後 會有一 4 × 4 的矩陣。為了要讓 Decoder 在見到 1 時預測 2, 3, 4 ，我們應該要將 (0, 1), (0, 2), (0, 3) 掩蓋。<br>見到 2 時，(1, 2), (1, 3) 應該要被掩蓋，以此類推。最終我們會得到一個上三角形，即為 Sequence Mask。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*lGtVw1yq5YzpaQFCR0t6qg.png" /><figcaption>Sequence Mask</figcaption></figure><p>之後我們知道，除了這種中規中矩的使用，之後的 BERT 更直接隨機 mask out tokens 作為 pre-trained task，也就是 MLM 。近日，<a href="https://arxiv.org/abs/2009.07118">It’s Not Just Size That Matters: Small Language Models Are Also Few-Shot Learners</a> 更讓 MLM 大放異彩。</p><h3>Why Self-Attention</h3><p>總結 Self-Attention 優於傳統 Encoder or Decoder 的理由：</p><h4>Less computation and easier to parallelize</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*2MnmZmig5LT_Kf8UoOLdow.png" /><figcaption>Layer Complexity</figcaption></figure><p>同 Introduction 所述，LSTM 必須要知道 t-1 時刻的狀態，無論是 c, h 或 x，才能計算 t 時刻，這樣的演算法本身就是 sequential ，無法平行化。但 Attention 本質上只是矩陣運算，很容易能夠做到軟體和硬體的最佳化。</p><p>除此之外，per-layer 的運算也較 convolution 和 recurrent 要少。但我認為這邊單純只比較 per-layer 的運算太過獨斷，應該也要比較 efficiency 才對，efficiency / complexity 才會是有效的比較。</p><h4>Short path to any positions in sequence</h4><p>我們曾在 Introduction 提到，Attention 更能夠學習到 global dependencies，因為任一 token 到另一 token 的「距離」非常短。</p><p>何謂距離？我個人理解為 embedding vector1 與 embedding vector2 使用該操作 encode 兩者的交互訊息時。</p><p>譬如 (8, 64, 64) 在 convolution 上，當 k = 2, s = k 不使用 padding 時，最多需要 6 次 convolution 操作才能確保序列頭尾的訊息被 encode 到 convolution。</p><p>而 LSTM 對於 (8, 64, num_feature)，則需要 64 次的操作才將序列頭尾的資訊 encode。</p><p>在 Attention Layer 中，由於是 dot-product ，(8, 64, 64) 的輸入 V，與 (8, 64, 64) 的 QK^T 直接相乘，所以在 QK^T (0, 63) 的這個值即 encode 序列頭尾的交互訊息了。</p><h4>More interpretable</h4><p>事實上，我是由電腦視覺中的 channel-wise attention 認識 Self-Attention 機制的，應該是透過 <a href="https://arxiv.org/abs/1809.02983">Dual Attention Network for Scene Segmentation</a>。其哲學很簡單，channels 之間必定存在聯繫，透過 self-attention 計算各個 channel 之間的聯繫並得出新的 channels。</p><p>就這樣的理解，QK^T 得出的是各個 tokens 之間的加權，視任務需要去賦予定義。如翻譯任務或文意理解，加權可以被解釋為相似性；對於 Q/A 任務，加權是對於輸出答案的幫助程度。所以我們當然可以透過 QK^T 的值做更多的 interpretation。</p><h3>Self-Attention Thoughts Under the Hood</h3><p>如上段理解，Query 與 Key 的作用為決定 Value 的權重，而 Key 與 Value 組成一個 token(註)。當 Query 與 Key 在該任務上有強烈的關聯，Key 所對應的 Value 就會被放大。</p><p>以此來理解 Decoder 中，Encoder 的輸出作為 Query 及 Key ，而經 Decoder 處理的輸入作為 Value ，可以解釋為，Encoder 的任務為決定哪些 token 對任務更有幫助，而 Decoder 則決定該 token 上 context vector 值的大小。</p><blockquote>An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.</blockquote><h3>Reference</h3><p>[1] Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translationr. <a href="https://arxiv.org/abs/1406.1078v3">arXiv:1406.1078v3</a> (2014).</p><p>[2] Neural machine translation by joint learning to align and translate. <a href="https://arxiv.org/abs/1409.0473v7">arXiv:1409.0473v7</a> (2016)</p><p>[3] <a href="https://medium.com/@bgg/seq2seq-pay-attention-to-self-attention-part-2-%E4%B8%AD%E6%96%87%E7%89%88-ef2ddf8597a4">Seq2seq pay Attention to Self Attention: Part 2(中文版)</a>, credits to <a href="https://medium.com/@bgg?source=post_page-----ef2ddf8597a4--------------------------------">Ta-Chun (Bgg/Gene) Su</a></p><p>本篇之 Transformer 僅僅是開始，其後的 Bert, GPT 和 Transformers review等文都值得一讀。</p><p>而在我寫下這篇文的一個禮拜前，ICLR 2021 已經將其正在進行 double-blind review 的論文放出，其中的 <a href="https://openreview.net/forum?id=YicbFdNTTy">AN IMAGE IS WORTH 16X16 WORDS: TRANSFORMERS FOR IMAGE RECOGNITION AT SCALE</a> 號稱能夠使用 Attention 機制就勝過傳統 Convolution-based CV model。是否真的 “Attention is all you need” ？值得拭目以待。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62a1c93c48a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7/review-attention-is-all-you-need-62a1c93c48a5">Review: Attention is all you need</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E4%BA%BA%E6%99%BA%E6%85%A7">工人智慧</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>