<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><div>
<p style="text-align:center">
    <img src="https://img0.tuicool.com/fieYjqq.jpg!web" class="alignCenter" referrerpolicy="no-referrer"/>
</p>

    <span>本文爲預訓練語言模型專題系列第九篇</span>




            <span>快速傳送門</span>
                    <strong mpa-from-tpl="t">  </strong>
        <span> </span>
1-4:[萌芽時代]、 [風起雲湧][文本分類通用技巧] [GPT家族] 5-8:[BERT來臨]、 [淺析BERT代碼][ERNIE合集] 、[ MT-DNN(KD) ]
    <span>感謝清華大學自然語言處理實驗室對</span>
    <strong>預訓練語言模型架構</strong>
    <span>的梳理,我們將沿此脈絡前行,探索預訓練語言模型的前沿技術,紅框中爲已介紹的文章,本期將結合HuggingFace代碼淺析Transformer代碼,歡迎大家留言討論交流。</span>

<p style="text-align:center">
    <img src="https://img2.tuicool.com/BVbuEn6.png!web" class="alignCenter" referrerpolicy="no-referrer"/>
</p>

    1

        <span>
            <strong>前言</strong>
        </span>


    <span>
        <span>
前面幾期一起分享了這麼多基於 Transformer 的預訓練語言模型,本期想和大家一起來結合代碼複習一下Transformer。它是目前state-of art 語言模型中最核心的模塊,替代RNN成爲NLP的柱石。
    <span>
        <span>我在分享中會引用HuggingFace Transformers包中的代碼,主要是BertAttention的相關代碼,希望大家也能有所收穫。</span>
    </span>


    2
    Attention Is All You Need(2017)

    <span>以前,處理NLP時序序列的關鍵模塊是循環神經網絡RNN(LSTM)或者卷積神經網絡CNN。但是它們都有各自的問題。比如RNN無法進行並行計算,訓練速度較慢,而且梯度傳遞有困難,容易梯度爆炸或消失。而卷積神經網絡難以捕捉長距離的語義。所以,這篇文章提出了一種新的簡單網絡結構,稱爲Transformer,單純基於attention的機制,既能並行計算提高訓練速度,還能夠捕捉句中的長序文本內部的聯繫。</span>


    <span>
        <span>直接上結構圖:</span>
    </span>

<p style="text-align:center">
    <img src="https://img2.tuicool.com/zqe26ze.png!web" class="alignCenter" referrerpolicy="no-referrer"/>
</p>
<h4>Encoder-decoder</h4>

    <span>首先它是一個encoder-decoder的結構。從設計上看,左邊的inputs會被encode成向量表示z,輸入給右邊decoder(encoder上方流出)。在解碼的時候,decoder會結合z和outputs中某token之前的token來生成當前的token,是比較典型的自迴歸模型。我們分別說說它的encoder以及decoder。</span>

<ul>
    <li>

            Encoder:
首先在Transformer的encoder裏有六層,每一層都是圖中這樣的兩個sublayer。第一個sublayer是一個Multi-Head Attention,第二個sublayer是feed forward layer。在這兩個sublayer之間都有 殘差連接和層歸一化
  •             Decoder:
    
    decoder也是六層,比起encoder有兩個變化,一是第一個sublayer的multi-head attention需要進行mask,因爲作爲一個自迴歸模型在decode的時候,每個詞的生成時,後面的詞還沒有生成出來,所以attention只能看到前面的詞,後面的需要被mask掉。二是中間插了一個新層來 計算encoder傳來的向量與output向量的attention
  • Attention

        <span>
    
    Transformers的精華就是Attention,接下來會結合論文和代碼來介紹 attention 的基本概念和用法。
    <p style="text-align:center">
        <img src="https://img0.tuicool.com/iiuEFjY.png!web" class="alignCenter" referrerpolicy="no-referrer"/>
    </p>
    
        <span>上圖左側的叫做</span>
        <strong>Scaled Dot-Product Attention</strong>
        <span>。</span>
        <span>計算的公式可以表示爲下圖,Q和K兩矩陣相乘後進行scale,scale的因子dk爲單個頭的維度,也即是上述代碼中的attention_head_size,矩陣乘V得到Attention的向量表達。</span>
    
    <p style="text-align:center">
        <img src="https://img2.tuicool.com/UvM3I3M.png!web" class="alignCenter" referrerpolicy="no-referrer"/>
    </p>
    
        <span>
            <span>這裏我們結合Transformers這個包BertSelfAttention類的代碼來具體討論</span>
    
    。首先定義三個矩陣 query, key, value。參數量和hidden_size和 head的數量有關,關於head我們後面再提。L爲文本長度。
    <pre class="prettyprint"><span><span># 頭的數量,以及每個頭的size</span></span>
    
    self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size # 三個變換矩陣 self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size)

    這裏定義的三個矩陣,實際上是要將某句文本的hidden_states變換成Q, K, V的表示,下面的代碼中是具體的變換和計算。

    # 將x從(batch_size, L, all_head_size)變爲(batch_size, num_heads, L, attention_size)
    
    def transpose_for_scores(self.x):
    
        new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
    
        x = x.view(*new_x_shape)
    
        return x.permute(0, 2, 1, 3)
    
    # 對hidden_states進行三種變換,形成Q, K, V
    
    mixed_query_layer = self.query(hidden_states)
    
    mixed_key_layer = self.key(hidden_states)
    
    mixed_value_layer = self.value(hidden_states)
    
    
    query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) # Q和K相乘得到本文自注意力的評分 attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: attention_scores = attention_scores + attention_mask
    # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores)
    # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs)
    # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask # softmax過的attention_prob乘V得到Attention的表示向量 context_layer = torch.matmul(attention_probs, value_layer)

    結合上面代碼中,我們可以觀察到

    1. hidden_states的shape是(batch_size, L, hidden_size) 。爲文本產生的向量表示如Embedding。

    2. 我們通過query矩陣乘hidden_state得到mixed_query_layer (batch_size, L, all_head_size)

    3. 經過 transpose變化成爲query_layer(batch_size, num_heads, L, attention_head_size) 得到上圖中的 Q

    4. 同樣的 key_layer(上圖中K)的shape爲(batch_size, num_heads, L, attention_head_size), 最後兩維包括文本長度的維度進行了矩陣相乘,所以attention_scores維度變爲(batch_size, num_heads, L, L)

    5. attention_score 經過softmax ,長度方向歸一化了,乘於value變爲context_layer(batch_size, num_heads, L, attention_head_size)

        <span>
    
    所以Q(query) ,K(key),V(value) 都是由原來文本向量乘於對應矩陣得到。這三種變換的矩陣參數都是我們需要通過訓練學習。Q矩陣乘K以後,得到(batch_size, num_heads, L, L)的矩陣,我理解爲文本的每個位置和其他位置都相乘得出一個數值,這個數值我們可以看作文本的每個token和其他token的相關度,即爲self attention的 score ,越大一般這兩個token關係就越密切,softmax以後變成一個0-1的數,這時候score再矩陣乘value我們就可以得到一個上下文相關向量的attention表示了。
        <span>
            <span>前面還提到了</span>
            <strong>Multi-Head Attention</strong>
            <span>,多頭注意力。相比於進行一次attention function,進行h次效果會更好。也就是說,我們會初始化h個不同的query, key, value矩陣,每個大小爲(hidden_state, attention_head_size), 在上面代碼中,我們實際上初始了一個(hidden_state, attention_head_size * num_heads) 大小的矩陣,與num_heads(h)個單頭的attention矩陣是一致的,矩陣中其實參數是單頭的num_heads份。然後每份參數去進行上面的attention運算,最後把多份的attention 拼接起來成爲了最終的multi-head attention。</span>
        </span>
    
    <h4>Positional Encoding</h4>
    
        <span>
            <span>
    
    Attention機制讓Transformer 得以能夠建立長距離的語義關聯,但是我們可以注意到,在encoder和decoder中,我們用的都是fully connected layer,所以每個位置的token都是獨立的,你會失去語序的信息。所以有必要告訴網絡,token之間的相對或絕對信息,所以文章引入了 Positional Encoding
    <p style="text-align:center">
        <img src="https://img0.tuicool.com/fmy2uqR.png!web" class="alignCenter" referrerpolicy="no-referrer"/>
    </p>
    
        <span>pos是位置,i是Embedding的某個維度, 2i指的偶數維度的Embedding, 2i+1指的是奇數維度的Embedding。i 是從 0到 dmodel / 2 ,所以對不同層的Embedding,sin和cos函數的波長是從 2pi 到 20000 pi。對於固定的i,  pos變化就會引起Embedding以正弦或餘弦變化。這樣encode了以後,模型就能去對相對的位置進行建模。</span>
    
    <h4>Visualizations</h4>
    
        <span>
    
    Attention的另外一個好處是, 可視化和可解釋性 加強了。我們從下圖可以看到masking這個詞,它主要和周圍的詞產生比較強的聯繫,尤其是和more difficult關係較大,這個是比較合理。我們還可以看到的是不同顏色代表不同的是不同的頭,不同頭的結果其實差別挺大的,這也是爲什麼多頭注意力能帶來收益的原因。
    <p style="text-align:center">
        <img src="https://img0.tuicool.com/jM3QV3M.png!web" class="alignCenter" referrerpolicy="no-referrer"/>
    </p>
    從下面這張圖,我們可以看到attention基本可以捕捉句子的結構。  
    <p style="text-align:center">
        <img src="https://img0.tuicool.com/Ire2aav.png!web" class="alignCenter" referrerpolicy="no-referrer"/>
    </p>
    
        <span>最後,作者比較了不同任務上Transformer的效果,我就貼出在機器翻譯上的結果,顯示Transformer確實在效果和效率上都有所提升。</span>
    
    <p style="text-align:center">
        <img src="https://img2.tuicool.com/FBjQFfY.png!web" class="alignCenter" referrerpolicy="no-referrer"/>
    </p>
    
        <span>
            <strong mpa-from-tpl="t" mpa-is-content="t">未完待續</strong>
        </span>
    
    
        <span md-inline="plain">本期的論文就給大家分享到這裏,感謝大家的閱讀和支持,下期我們會給大家帶來其他預訓練語言模型的介紹,敬請大家期待!</span>
    
    
        <span>
            <strong>推薦閱讀</strong>
        </span>
        <strong/>
    
    
        <span>
            <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412170&amp;idx=1&amp;sn=67ca8bd3235f647bb4f613a5501015f1&amp;chksm=becd92d089ba1bc63198c3c531dec05dd21a1e71a2333a4f938fe91566c9085173832255946e&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">AINLP年度閱讀收藏清單</a>
        </span>
    
    
        <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412822&amp;idx=1&amp;sn=615917ca3062c6afb0ec69557a6886da&amp;chksm=becd914c89ba185a20e359b1114eccc9e0c6c84a6b7ec596e92fdd532910c5b1fe34c47000fb&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">百度PaddleHub&amp;nbsp;NLP模型全面升級,推理性能提升50%以上</a>
    
    
        <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412817&amp;idx=1&amp;sn=fdff8ce7a673bb11139c2957383abf48&amp;chksm=becd914b89ba185dc05669440e15422b299972a5a8c5da41fcc274f865e3ba076610bdf0a527&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">斯坦福大學NLP組Python深度學習自然語言處理工具Stanza試用</a>
    
    
        <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412733&amp;idx=1&amp;sn=2c36b607e1f2d87d6819cdd9028e4da5&amp;chksm=becd90e789ba19f127e9cb58f8518847aa758dcc802f028c2a8d451dbdc92774c373e9fd24f1&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">數學之美中盛讚的 Michael Collins 教授,他的NLP課程要不要收藏?</a>
    
    
        <span>
            <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412689&amp;idx=2&amp;sn=f7cc853175a2a31a12feb169be0e61ff&amp;chksm=becd90cb89ba19dd629b0e03c94a54c8902b9d9f1ba595a3d0bfd75a69ed2a975fe2d1251b86&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">自動作詩機&amp;藏頭詩生成器:五言、七言、絕句、律詩全了</a>
        </span>
    
    
        <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412641&amp;idx=2&amp;sn=1c5eb86ab9be36905ff68c70b8bb89ec&amp;chksm=becd903b89ba192d987307313d75b086231e074bd4a94fb3a01e67af62c0270f0125fd5996bd&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">From Word Embeddings To Document Distances 閱讀筆記</a>
    
    
        <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412629&amp;idx=1&amp;sn=d5e182941286af6adb745d8393f35151&amp;chksm=becd900f89ba19199ac6c4fb31a2717d05363ebdbf5371f5dd5ec03d6af1e4ddd28c1dc1ad35&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">模型壓縮實踐系列之——bert-of-theseus,一個非常親民的bert壓縮方法</a>
    
    
        <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412635&amp;idx=1&amp;sn=6712b9c4bb5f0e7678f5475fb2d7defb&amp;chksm=becd900189ba1917f87709d59275d8871fc01c102b6c9c3f6ff999ab7aa891b30384e5d13a02&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">這門斯坦福大學自然語言處理經典入門課,我放到B站了</a>
    
    
        <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412195&amp;idx=2&amp;sn=5363c291223c99f537fc3ea8a951829f&amp;chksm=becd92f989ba1beff71076a5d98ecebc950026186d88d73a010b306961da357054a6db1019ee&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">
            <span>可解釋性論文閱讀筆記1-Tree Regularization</span>
        </a>
    
    
        <a target="_blank" href="http://mp.weixin.qq.com/s?__biz=MjM5ODkzMzMwMQ==&amp;mid=2650412214&amp;idx=2&amp;sn=4bcf51e1e267290cae8e29c53a102851&amp;chksm=becd92ec89ba1bfad686b2381a47f7da7332d61d22c11779dcb5b59d926412098e4e424af17a&amp;scene=21#wechat_redirect" tab="innerlink" hasload="1" rel="nofollow,noindex">徵稿啓示 | 稿費+GPU算力+星球嘉賓一個都不少</a>
    
    <h4>關於AINLP</h4>
    AINLP 是一個有趣有AI的自然語言處理社區,專注於 AI、NLP、機器學習、深度學習、推薦算法等相關技術的分享,主題包括文本摘要、智能問答、聊天機器人、機器翻譯、自動生成、知識圖譜、預訓練模型、推薦系統、計算廣告、招聘信息、求職經驗分享等,歡迎關注!加技術交流羣請添加AINLPer(id:ainlper),備註工作/研究方向+加羣目的。
    <p style="text-align:center">
        <img src="https://img1.tuicool.com/qIR3Abr.jpg!web" class="alignCenter" referrerpolicy="no-referrer"/>
    </p>
    
    相關文章