Zhangzhe's Blog

The projection of my life.

0%

T5: Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer

URL

TL;DR

  • T5 名字的由来是:Text-to-Text Transfer Transformer文本到文本转换的 Transformer

Algorithm

example

  • T5 是一个 encoder-decoder 架构的模型,可以用来做文本翻译,本例子使用 Hello, world! 英语翻译法语为例

0. prompt

  • prompt 的作用是在输入之前加上对任务的描述
  • 比如 english_to_franch("Hello, world!") API 会被 prompt"translate English to French: Hello, world!" 纯文本输入到模型

1. encoder input tokenize

2. encoder input token embedding

  • GPT 系列没有区别,需要把 encoder input token id 查表变成 token embedding

3. encoder input position encoding

  • GPT 系列使用可学习的 position embedding 不同,T5 使用的是 position encoding
  • 且使用的是相对位置编码,而不是绝对位置编码
  • GPT 系列只在模型 casual decoder 第一层输入加入 position embedding 不同,T5position encoding 是在 encoder 以及 decoder 的每一层都是使用了

4. encoder

  • GPT 系列直接使用 token embedding + position embedding 直接得到 hidden state 来输入 decoder 不同,T5encoder 结构
  • T5encoder 结构采用标准 transformer encoder 结构,每个 token 可以看到所有 token
  • encoder 一共 12 层,每一层包括如下顺序结构为:
    • self attention block
      • layer norm
      • self attention
      • dropout
    • FFN
      • layer norm
      • MLP
      • dropout
  • encoder 最终输出一个 shape = (batch, input_token_len, encoder_dim)encoder hidden state

5. decoder input token embedding and position encoding

  • GPT 系列不同之处在于 T5decoder 阶段需要 decoder input
  • 通常情况下 decoder input<BOS><S> 等特殊标记,token 长度仅仅为 1,用于表示序列开始
  • decoder input token embeddingposition encoding 过程和 encoder input token embeddingposition encoding 并无区别
  • token embedding + position encoding 得到 decoder hidden state,其 shape = (batch, 1, decoder_dim)

6. decoder

  • decoder 一共 12 层,每一层包括如下顺序结构为:
    • self attention block
      • layer norm
      • self attention
      • dropout
    • cross attention block
      • layer norm
      • self attention
      • dropout
    • FFN
      • layer norm
      • MLP
      • dropout
  • 其中 self attention 的输入是 decoder hidden state注意不是 encoder hidden state
  • decoder hidden stateencoder hidden state 输入到 cross attention中,Cross attentionSelf attention 实际上只有一个区别:
    • self attentionquery / key / value 都由同一个 hidden state 得到,因此称为 self
    • cross attentionkey / value 由同一个 hidden state 得到,query 由另一个 hidden state 得到,因此称为 cross
    • encoder-decoder 架构的 transformer 中,decoder 中的 cross attentionkey / value 通常由 encoder output hidden state 得到,query 通常由 decoder hidden state 得到
  • 重复跑完 12 层,最终输出 shape = (batch, 1, decoder_dim)decoder output hidden state

7. decoder output hidden state to token

  • 需要将 docoder output hidden state 用一层 MLP 转化到 vocabulary 空间,找到最可能的一个 token
  • token 对应的单词即为模型最终输出的第一个词。
  • 如果这个词是词表中的结束符,则停止输出。如果不是,则用此词替代前一个词,重复上述的 5. decoder input token embedding and position encoding6. decoder7. decoder output hidden state to token 过程,直到达到最长输出长度限制或出现停止符。