{"notes":[{"id":"transformers/transformer","category":"transformers","legacyPath":"transformers/1706-transformer","legacySlug":"1706-transformer","legacyPaths":[],"title":"Transformer","subtitle":"The Dawn of a New Era","author":"Z. Yuan","paperDate":"2017-06-12","publishedOn":"2024-05-05","paperTitle":"Attention Is All You Need","paperUrl":"https://arxiv.org/abs/1706.03762","bibliography":{"title":"Attention Is All You Need","authors":["Ashish Vaswani","Noam Shazeer","Niki Parmar","Jakob Uszkoreit","Llion Jones","Aidan N. Gomez","Lukasz Kaiser","Illia Polosukhin"],"url":"https://arxiv.org/abs/1706.03762","pdfUrl":"https://arxiv.org/pdf/1706.03762","codeUrl":null,"preprint":{"id":"1706.03762","submittedOn":"2017-06-12","url":"https://arxiv.org/abs/1706.03762"},"publication":{"venue":"NeurIPS (NIPS)","year":2017,"kind":"conference","url":"https://proceedings.neurips.cc/paper_files/paper/2017/hash/3f5ee243547dee91fbd053c1c4a845aa-Abstract.html"},"citation":"@misc{transformerstransformer2017,\n  title = {{Attention Is All You Need}},\n  author = {Ashish Vaswani and Noam Shazeer and Niki Parmar and Jakob Uszkoreit and Llion Jones and Aidan N. Gomez and Lukasz Kaiser and Illia Polosukhin},\n  year = {2017},\n  eprint = {1706.03762},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1706.03762}\n}\n","citationPath":"/content/papers/citations/transformers/transformer.86c0068d96fd.bib"},"thumbnail":{"src":"/content/papers/assets/29a55cb05497bdd9bbb3f3a96b7ed6656fda3552fa6a0fa5eb29e8e899c1acc1.jpg","width":756,"height":1080},"locale":"en","path":"/content/papers/en/transformers/transformer.420ab06f9af4.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"model-design","text":"Model Design","depth":3},{"id":"input-layer","text":"Input Layer","depth":3},{"id":"positional-encoding","text":"Positional Encoding","depth":3},{"id":"self-attention-mechanism","text":"Self-Attention Mechanism","depth":3},{"id":"multi-head-attention-mechanism","text":"Multi-Head Attention Mechanism","depth":3},{"id":"cross-attention-mechanism","text":"Cross-Attention Mechanism","depth":3},{"id":"feed-forward-network","text":"Feed-Forward Network","depth":3},{"id":"layer-normalization","text":"Layer Normalization","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"why-use-self-attention","text":"Why Use Self-Attention?","depth":3},{"id":"experimental-results-machine-translation","text":"Experimental Results: Machine Translation","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/flashattention","relation":"next","topic":"Attention memory and computation"},{"id":"transformers/bert","relation":"next","topic":"Pretraining bidirectional language representations"},{"id":"transformers/gpt_1","relation":"next","topic":"From language pretraining to in-context learning"}]},{"id":"transformers/flashattention","category":"transformers","legacyPath":"","legacySlug":"","legacyPaths":[],"title":"FlashAttention","subtitle":"Recompute to go faster","author":"Z. Yuan","paperDate":"2022-05-27","publishedOn":"2023-10-14","paperTitle":"FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness","paperUrl":"https://papers.nips.cc/paper_files/paper/2022/hash/67d57c32e20fd0a7a302cb81d36e40d5-Abstract-Conference.html","bibliography":{"title":"FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness","authors":["Tri Dao","Daniel Y. Fu","Stefano Ermon","Atri Rudra","Christopher Ré"],"url":"https://papers.nips.cc/paper_files/paper/2022/hash/67d57c32e20fd0a7a302cb81d36e40d5-Abstract-Conference.html","pdfUrl":"https://papers.nips.cc/paper_files/paper/2022/file/67d57c32e20fd0a7a302cb81d36e40d5-Paper-Conference.pdf","codeUrl":"https://github.com/Dao-AILab/flash-attention","preprint":{"id":"2205.14135","submittedOn":"2022-05-27","url":"https://arxiv.org/abs/2205.14135"},"publication":{"venue":"NeurIPS","year":2022,"kind":"conference","url":"https://papers.nips.cc/paper_files/paper/2022/hash/67d57c32e20fd0a7a302cb81d36e40d5-Abstract-Conference.html"},"citation":"@misc{transformersflashattention2022,\n  title = {{FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness}},\n  author = {Tri Dao and Daniel Y. Fu and Stefano Ermon and Atri Rudra and Christopher Ré},\n  year = {2022},\n  eprint = {2205.14135},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2205.14135}\n}\n","citationPath":"/content/papers/citations/transformers/flashattention.c58786df0331.bib"},"thumbnail":{"src":"/content/papers/assets/0df05e80bbc932893fde60a74e418e29ea95d39830ad1bf354eda2c19415b346.png","width":473,"height":482},"locale":"en","path":"/content/papers/en/transformers/flashattention.28697b5aad5c.md","headings":[{"id":"the-problem","text":"The problem","depth":2},{"id":"the-method","text":"The method","depth":2},{"id":"meet-the-three-matrices","text":"Meet the three matrices","depth":3},{"id":"four-scores-two-passes","text":"Four scores, two passes","depth":3},{"id":"during-training-calculate-it-again","text":"During training, calculate it again","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"more-arithmetic-less-waiting","text":"More arithmetic, less waiting","depth":3},{"id":"does-another-gpu-give-the-same-answer","text":"Does another GPU give the same answer?","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/transformer","relation":"background","topic":"Attention memory and computation"},{"id":"transformers/flashattention2","relation":"next","topic":"Attention memory and computation"}]},{"id":"transformers/bert","category":"transformers","legacyPath":"transformers/1810-bert","legacySlug":"1810-bert","legacyPaths":[],"title":"BERT","subtitle":"Twelve Layers of Encoders","author":"Z. Yuan","paperDate":"2018-10-11","publishedOn":"2024-05-12","paperTitle":"BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding","paperUrl":"https://arxiv.org/abs/1810.04805","bibliography":{"title":"BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding","authors":["Jacob Devlin","Ming-Wei Chang","Kenton Lee","Kristina Toutanova"],"url":"https://arxiv.org/abs/1810.04805","pdfUrl":"https://arxiv.org/pdf/1810.04805","codeUrl":null,"preprint":{"id":"1810.04805","submittedOn":"2018-10-11","url":"https://arxiv.org/abs/1810.04805"},"publication":{"venue":"NAACL-HLT","year":2019,"kind":"conference","url":"https://doi.org/10.18653/v1/n19-1423"},"citation":"@misc{transformersbert2018,\n  title = {{BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding}},\n  author = {Jacob Devlin and Ming-Wei Chang and Kenton Lee and Kristina Toutanova},\n  year = {2018},\n  eprint = {1810.04805},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1810.04805}\n}\n","citationPath":"/content/papers/citations/transformers/bert.d9bf47a21c5f.bib"},"thumbnail":{"src":"/content/papers/assets/57ed95afec24d2732e290d4fcb5633e14a2bbe74b83c6b6cdee90ef44ac89411.jpg","width":1224,"height":396},"locale":"en","path":"/content/papers/en/transformers/bert.75ec0229da6b.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"unidirectionality","text":"Unidirectionality","depth":3},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"pre-training-strategy","text":"Pre-training Strategy","depth":3},{"id":"fine-tuning-strategy","text":"Fine-tuning Strategy","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"ablation-study","text":"Ablation Study","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/transformer","relation":"background","topic":"Pretraining bidirectional language representations"},{"id":"transformers/roberta","relation":"next","topic":"Pretraining bidirectional language representations"},{"id":"transformers/albert","relation":"comparison","topic":"Training and compressing BERT"}]},{"id":"transformers/gpt_1","category":"transformers","legacyPath":"transformers/1806-gpt_1","legacySlug":"1806-gpt_1","legacyPaths":[],"title":"GPT-1","subtitle":"Twelve-Layer Decoder","author":"Z. Yuan","paperDate":"2018","publishedOn":"2024-05-05","paperTitle":"Improving Language Understanding by Generative Pre-Training","paperUrl":"https://openai.com/index/language-unsupervised/","bibliography":{"title":"Improving Language Understanding by Generative Pre-Training","authors":["Alec Radford","Karthik Narasimhan","Tim Salimans","Ilya Sutskever"],"url":"https://openai.com/index/language-unsupervised/","pdfUrl":"https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf","codeUrl":"https://github.com/openai/finetune","preprint":null,"publication":{"venue":"OpenAI","year":2018,"kind":"report","url":"https://openai.com/index/language-unsupervised/"},"citation":"@techreport{transformersgpt12018,\n  title = {{Improving Language Understanding by Generative Pre-Training}},\n  author = {Alec Radford and Karthik Narasimhan and Tim Salimans and Ilya Sutskever},\n  year = {2018},\n  institution = {OpenAI},\n  url = {https://openai.com/index/language-unsupervised/}\n}\n","citationPath":"/content/papers/citations/transformers/gpt_1.634f01e1da35.bib"},"thumbnail":{"src":"/content/papers/assets/09638f2c9f2ddf16a7510c19cd888dd53d93ebd8746b94742b311fdb192fc66a.jpg","width":1224,"height":620},"locale":"en","path":"/content/papers/en/transformers/gpt_1.d7c445890019.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"1-lack-of-labeled-data","text":"1. Lack of Labeled Data","depth":3},{"id":"2-task-inconsistency","text":"2. Task Inconsistency","depth":3},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"pre-training-strategy","text":"Pre-training Strategy","depth":3},{"id":"fine-tuning-strategy","text":"Fine-tuning Strategy","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"why-is-the-transformer-effective","text":"Why is the Transformer Effective?","depth":3},{"id":"which-part-is-effective","text":"Which Part is Effective?","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/transformer","relation":"background","topic":"From language pretraining to in-context learning"},{"id":"transformers/gpt_2","relation":"next","topic":"From language pretraining to in-context learning"}]}],"text":"Unlike previous sequential models, the Transformer model introduced a new era of self-attention mechanisms.\n\nThe model replaces recurrent sequence computation with attention, allowing positions to be processed in parallel during training. Its original autoregressive decoder still generates tokens sequentially at inference time.\n\n## Problem Definition\n\nIn previous sequence modeling tasks, RNN and LSTM models were the mainstream.\n\nHowever, these models have some issues during training and inference:\n\n- **Limitations of Recurrent Computation**: RNN and LSTM models require step-by-step computation of each element in the sequence during training, which makes it difficult for the models to perform efficient parallel computation.\n- **Long-Distance Dependency Problem**: Due to the recurrent computation of RNN and LSTM models, they struggle to capture dependencies between distant positions in long sequences.\n\n## Solving the Problem\n\n### Model Design\n\n\n\n![Transformer Model Architecture](/content/papers/assets/29a55cb05497bdd9bbb3f3a96b7ed6656fda3552fa6a0fa5eb29e8e899c1acc1.jpg)\n\n\n\nThis is the Transformer model architecture diagram provided in the original paper.\n\nAlthough this diagram is very concise (???), most people usually do not understand it at first glance.\n\nBelieve it or not, this is already simplified!\n\nLet's write a simple code snippet to see how this model actually works:\n\n### Input Layer\n\nHere, the input is a sequence of data, represented as a tensor.\n\n- First dimension: Batch size, referred to as `B`.\n- Second dimension: Sequence length, referred to as `T`.\n- Third dimension: Feature dimension, referred to as `D`.\n\nLet's start with a simple example:\n\n```python\ninput_text = ['你', '好', '啊', '。']\ninput_text_mapping = {\n    '你': 0,\n    '好': 1,\n    '啊': 2,\n    '。': 3\n}\n```\n\nIn this example, the input text is \"你好啊。\", with a total of 4 characters.\n\n\n> [!NOTE]\n> \n> Here, we greatly simplify the entire training process to make it easier for you to understand.\n\n\nNext, convert this input into a tensor:\n\n```python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ninput_tensor = torch.tensor([\n    input_text_mapping[token]\n    for token in input_text]\n)\nprint(input_tensor)\n# >>> tensor([0, 1, 2, 3])\n```\n\nNext, we embed each element:\n\n```python\nembedding = nn.Embedding(num_embeddings=4, embedding_dim=512)\nembedded_input = embedding(input_tensor)\nprint(embedded_input)\n# Example values only; actual values depend on initialization.\n# >>> tensor([[ 0.1,  0.2,  0.3,  ...,  0.4],\n#             [ 0.5,  0.6,  0.7,  ...,  0.8],\n#             [ 0.9,  1.0,  1.1,  ...,  1.2],\n#             [ 1.3,  1.4,  1.5,  ...,  1.6]])\nprint(embedded_input.shape)\n# >>> torch.Size([4, 512])\n```\n\n\n> [!TIP]\n> \n> An embedding is a trainable lookup table: each token ID selects one row. This is equivalent to multiplying a one-hot vector by a weight matrix, not applying a linear layer directly to the integer ID.\n\n\nFinally, don't forget we need a 3D tensor as input, so we need to add a batch size dimension. In this example, the batch size is 1.\n\n```python\nembedded_input = embedded_input.unsqueeze(0)\nprint(embedded_input.shape)\n# >>> torch.Size([1, 4, 512])\n```\n\n### Positional Encoding\n\nIn the original RNN and LSTM models, the model can capture dependencies in the sequence through the position of elements in the sequence. Therefore, we do not need to explicitly design positional encodings, as the model implicitly includes positional information during each iteration of the For-Loop.\n\nSelf-attention relates tokens by content. Without positional information, it cannot distinguish their order from content alone. Positional encoding supplies that missing information; the issue is not that the network contains only linear layers or cannot relate tokens.\n\nIn the paper, the authors propose a simple method for positional encoding using sine and cosine functions. For a given sequence position $pos$ and encoding dimension $i$, the positional encoding is calculated as:\n\n$$\nPE_{(pos, 2i)} = \\sin\\left(\\frac{pos}{10000^{\\frac{2i}{d_{model}}}}\\right)\n$$\n\n$$\nPE_{(pos, 2i+1)} = \\cos\\left(\\frac{pos}{10000^{\\frac{2i}{d_{model}}}}\\right)\n$$\n\nWhere:\n\n- $pos$ is the position of the element in the sequence (starting from 0).\n- $i$ indexes a sine/cosine pair, corresponding to dimensions $2i$ and $2i+1$.\n- $d_{model}$ is the dimension of the positional encoding (usually the same as the feature dimension of the model input).\n\nLet's implement a positional encoding function based on the above formula:\n\n```python\nimport math\nimport torch\n\ndef sinusoidal_positional_encoding(length, dim):\n    \"\"\" Sinusoidal positional encoding for non-recurrent neural networks.\n        REFERENCES: Attention Is All You Need\n        URL: https://arxiv.org/abs/1706.03762\n    \"\"\"\n    if dim % 2 != 0:\n        raise ValueError(\n            'Cannot use sin/cos positional encoding with '\n            f'odd dim (got dim={dim})')\n\n    # position embedding\n    pe = torch.zeros(length, dim)\n    position = torch.arange(0, length).unsqueeze(1)\n    div_term = torch.exp(\n        (torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim)))\n    pe[:, 0::2] = torch.sin(position.float() * div_term)\n    pe[:, 1::2] = torch.cos(position.float() * div_term)\n\n    return pe\n```\n\nThis function generates a fixed encoding from each position index and feature dimension; the sequence length determines how many position vectors to generate.\n\nLet's visualize the positional encoding, assuming a sequence length of 256 and a feature dimension of 512:\n\n```python\nimport cv2\nimport numpy as np\n\npos_mask = sinusoidal_positional_encoding(256, 512)\npos_mask = pos_mask.numpy()\npos_mask = (pos_mask - pos_mask.min()) / (pos_mask.max() - pos_mask.min())\npos_mask = np.array(pos_mask * 255).astype(np.uint8)\npos_mask = cv2.applyColorMap(pos_mask, cv2.COLORMAP_JET)\n```\n\n![Positional Encoding Visualization](/content/papers/assets/cf4e6199fed125463d1bf049f3b141519f2057fbc55bc50bc1cc461d0021e48f.jpg)\n\n\n> [!TIP]\n> \n> **What is the significance of the number 10000 in the formula?**\n> \n> The number 10000 is the frequency base. Reducing it raises the frequencies and shortens the periods in all but the highest-frequency pair, changing the distance scales represented across dimensions. This does not, by itself, prove that the full position vector repeats sooner or that long-range performance becomes worse; that depends on the model, data and length regime. The original paper motivates sinusoidal encoding through relative-position relationships, not a universal guarantee about this base.\n> \n\n\nAfter obtaining the positional encoding, we need to add it to the input embedding tensor:\n\n```python\npos_emb = sinusoidal_positional_encoding(4, 512)\nembedded_input = embedded_input * math.sqrt(512) + pos_emb\n```\n\n### Self-Attention Mechanism\n\nAfter obtaining the input encoding, we can move on to the core part of the Transformer model: the self-attention mechanism.\n\nHere, we need to prepare three transformation matrices:\n\n1. **Query Matrix `W_q`.**\n\n   First, declare a set of weights `W_q`, then multiply the input embedding tensor by the Query matrix to get the Query tensor.\n\n   ```python\n   W_q = nn.Linear(512, 512)\n   query = W_q(embedded_input)\n   print(query.shape)\n   # >>> torch.Size([1, 4, 512])\n   ```\n\n2. **Key Matrix `W_k`.**\n\n   Similarly, declare a set of weights `W_k`, then multiply the input embedding tensor by the Key matrix to get the Key tensor.\n\n   ```python\n   W_k = nn.Linear(512, 512)\n   key = W_k(embedded_input)\n   print(key.shape)\n   # >>> torch.Size([1, 4, 512])\n   ```\n\n3. **Value Matrix `W_v`.**\n\n   Finally, declare a set of weights `W_v`, then multiply the input embedding tensor by the Value matrix to get the Value tensor.\n\n   ```python\n   W_v = nn.Linear(512, 512)\n   value = W_v(embedded_input)\n   print(value.shape)\n   # >>> torch.Size([1, 4, 512])\n   ```\n\nSo, what exactly is this QKV stuff?\n\nYou can think of the transformation matrices as projections.\n\nProjections mean \"viewing from a different perspective.\"\n\nThe QKV process involves three different projections of the input, followed by the self-attention mechanism calculations.\n\n---\n\nThe second step of the self-attention mechanism is to calculate the attention scores.\n\n$$\n\\text{Attention}(Q, K, V) = \\text{softmax}\\left(\\frac{QK^\\top}{\\sqrt{d_k}}\\right)V\n$$\n\nIn this step, we perform a dot product between the Query tensor and the Key tensor.\n\n```python\nattn_maps = torch.matmul(query, key.transpose(-2, -1))\nprint(attn_maps.shape)\n# >>> torch.Size([1, 4, 4])\n```\n\nThis gives us an attention score matrix of size 4x4.\n\nIn this example, it explores the relationships between [你, 好, 啊, 。] (you, good, ah, .).\n\nThe factor `1/sqrt(d_k)` counteracts the growth in dot-product scale with dimension and helps avoid softmax saturation. Here the single head uses $d_k=512$; the later eight-head example uses 64 dimensions per head.\n\n```python\nattn_maps = attn_maps / math.sqrt(512)\n```\n\nNext is the Softmax operation:\n\n```python\nattn_maps = F.softmax(attn_maps, dim=-1)\n```\n\n\n> [!TIP]\n> \n> **Why use Softmax? Why not Sigmoid?**\n> \n> Softmax gives each query nonnegative weights that sum to 1 over its visible keys, yielding a weighted average. Sigmoid acts independently on each score and imposes no such sum constraint; it is not an equivalent replacement.\n\n\nAfter calculating the attention map, we can perform a weighted sum of the Value tensor:\n\n```python\nattn_output = torch.matmul(attn_maps, value)\nprint(attn_output.shape)\n# >>> torch.Size([1, 4, 512])\n```\n\nFinally, apply residual connections:\n\n```python\nresidual_output = embedded_input + attn_output\n```\n\n### Multi-Head Attention Mechanism\n\nA single head already gives each query a distribution over keys. But what if we want to examine several learned views of the sequence? That is the idea of multi-head attention: each head uses a different feature subspace.\n\n\n\n![Multi-Head Attention Mechanism](/content/papers/assets/d01504d88522dd473549eae49a6d150720d98697ddc74a076bc69bb125647edd.jpg)\n\n\n\nA common implementation packs the heads' projections into larger linear layers, then splits the projected tensors. This is equivalent to separate projections. The details are mostly engineering, so we will not dig further into them here; this runnable sketch just follows eight heads through concatenation and the output projection:\n\n```python\nnum_heads, head_dim = 8, 64\nbatch_size, seq_len, _ = query.shape\nQ = query.reshape(batch_size, seq_len, num_heads, head_dim).transpose(1, 2)\nK = key.reshape(batch_size, seq_len, num_heads, head_dim).transpose(1, 2)\nV = value.reshape(batch_size, seq_len, num_heads, head_dim).transpose(1, 2)\nweights = torch.softmax(Q @ K.transpose(-2, -1) / math.sqrt(head_dim), dim=-1)\nheads = weights @ V\nmerged = heads.transpose(1, 2).contiguous().reshape(batch_size, seq_len, 512)\noutput_projection = nn.Linear(512, 512)\nmultihead_output = output_projection(merged)\nprint(multihead_output.shape)\n# >>> torch.Size([1, 4, 512])\n```\n\nThe weights have shape `[B, 8, T, T]`. Each head operates in 64 dimensions; concatenation returns to 512 dimensions for the residual path.\n\n### Cross-Attention Mechanism\n\nIn the Transformer architecture, the attention mechanisms in the Encoder and Decoder are similar but have some differences.\n\nIn the Encoder, we perform self-attention calculations for each position in the sequence; in the Decoder, besides self-attention calculations for each position, we also need to perform attention calculations on the Encoder's output, which is known as **cross-attention**.\n\nEach decoder layer has masked self-attention, cross-attention and a feed-forward sublayer. Cross-attention takes Q from the preceding decoder sublayer and K/V from the final encoder output. The following random states illustrate shapes, not a complete decoder.\n\nAgain, we need to prepare three transformation matrices:\n\n1. **Query Matrix `W_q`.**\n\n   First, declare a set of weights `W_q`, project the Decoder state after masked self-attention with the Query matrix to get the Query tensor. The length of `decoder_input` can be different from `encoder_output`. If we encounter a translation problem, this length might be 10.\n\n   ```python\n   W_q = nn.Linear(512, 512)\n   decoder_input = torch.randn(1, 10, 512)  # decoder state after masked self-attention\n   encoder_output = torch.randn(1, 4, 512)  # final encoder state\n   decoder_query = W_q(decoder_input)\n   print(decoder_query.shape)\n   # >>> torch.Size([1, 10, 512])\n   ```\n\n\n> [!TIP]\n> \n> Here, the input is `decoder_input`.\n\n\n2. **Key Matrix `W_k`.**\n\n   Similarly, declare a set of weights `W_k`, multiply the Encoder's output embedding tensor by the Key matrix to get the Key tensor.\n\n   ```python\n   W_k = nn.Linear(512, 512)\n   encoder_key = W_k(encoder_output)\n   print(encoder_key.shape)\n   # >>> torch.Size([1, 4, 512])\n   ```\n\n\n> [!TIP]\n> \n> Here, the input is `encoder_output`.\n\n\n3. **Value Matrix `W_v`.**\n\n   Finally, declare a set of weights `W_v`, multiply the Encoder's output embedding tensor by the Value matrix to get the Value tensor.\n\n   ```python\n   W_v = nn.Linear(512, 512)\n   encoder_value = W_v(encoder_output)\n   print(encoder_value.shape)\n   # >>> torch.Size([1, 4, 512])\n   ```\n\n\n> [!TIP]\n> \n> Here, the input is `encoder_output`.\n\n\nThe subsequent steps are the same as the self-attention mechanism: first, calculate the attention map:\n\n```python\nattn_maps = torch.matmul(decoder_query, encoder_key.transpose(-2, -1))\nprint(attn_maps.shape)\n# >>> torch.Size([1, 10, 4])\n```\n\nThen, perform scaling and Softmax:\n\n```python\nattn_maps = attn_maps / math.sqrt(512)\nattn_maps = F.softmax(attn_maps, dim=-1)\n```\n\nFinally, perform a weighted sum of the Value tensor:\n\n```python\nattn_output = torch.matmul(attn_maps, encoder_value)\nprint(attn_maps.shape)\n# >>> torch.Size([1, 10, 4])\nprint(encoder_value.shape)\n# >>> torch.Size([1, 4, 512])\nprint(attn_output.shape)\n# >>> torch.Size([1, 10, 512])\n```\n\n\n> [!NOTE]\n> \n> In the self-attention phase of the Decoder, a mask operation is typically added to ensure that during decoding, future information cannot be seen. This mask is usually an upper triangular matrix, ensuring that the Decoder can only see the generated part during decoding.\n> \n> ```python\n> def causal_mask(length: int, device=None, dtype=torch.float32) -> torch.Tensor:\n>     return torch.triu(\n>         torch.full((length, length), float(\"-inf\"), device=device, dtype=dtype),\n>         diagonal=1,\n>     )\n> \n> # Add before softmax in DECODER SELF-attention, not encoder cross-attention.\n> mask = causal_mask(10)\n> ```\n> \n\n\n### Feed-Forward Network\n\nAfter the self-attention mechanism, we need to pass through a simple feed-forward network to extract features.\n\n```python\nffn = nn.Sequential(\n    nn.Linear(512, 2048),\n    nn.ReLU(),\n    nn.Linear(2048, 512)\n)\nffn_input = multihead_output\nffn_output = ffn(ffn_input)\noutput = ffn_input + ffn_output\nprint(output.shape)\n# >>> torch.Size([1, 4, 512])\n```\n\nThis feed-forward network is a typical fully connected network. Here, we use two fully connected layers with a ReLU activation function in between.\n\nAdditionally, there is an expand-dim operation in the module, usually with an expansion factor of 4. This operation is similar to the concept of the Inverted Residual Bottleneck Block proposed in MobileNet-V2. The main purpose is to improve the model's nonlinear representation ability by expanding the dimensions and then compressing them.\n\n### Layer Normalization\n\nWe haven't mentioned `LayerNorm` yet.\n\nThis operation is straightforward. After understanding all the steps above, it just takes a few lines of code.\n\nThe original Transformer uses Post-LN: residual addition followed by LayerNorm for each sublayer. Combining the earlier illustrations gives the following encoder layer. Add each residual once, and feed the first normalized state into the FFN. Dropout is omitted to focus on data flow.\n\n```python\nnorm1 = nn.LayerNorm(512)\nencoder_state = norm1(embedded_input + multihead_output)\n\n# ...\n\nnorm2 = nn.LayerNorm(512)\nffn_output = ffn(encoder_state)\noutput = norm2(encoder_state + ffn_output)\n```\n\n\n> [!TIP]\n> \n> **Why not use Batch Normalization?**\n> \n> LayerNorm computes statistics across each token's feature dimensions without relying on other batch members. This simplifies handling of batch size, sequence length and inference-time statistics.\n\n\n## Discussion\n\n### Why Use Self-Attention?\n\n\n\n![Attention](/content/papers/assets/05da9f1b22cfa674c685e532a517b699eac9d56ae0a208a6e32d16814de9353e.jpg)\n\n\n\nThe key advantage is parallel computation across positions during training. Full attention still has quadratic cost in sequence length, and autoregressive decoding remains sequential.\n\n---\n\nThe authors summarized the computational complexity of RNN, CNN, and Self-Attention, as shown in the figure above.\n\n1. **Self-Attention Layer (Unrestricted)**:\n\n   - **Per-layer complexity:** $\\mathcal{O}(n^2 \\cdot d)$: In the self-attention mechanism, each input token (with sequence length $n$) must compute attention with all other tokens, forming a complete $n \\times n$ attention matrix. Each matrix element requires computation based on a $d$-dimensional embedding, so the total complexity of the attention matrix is $\\mathcal{O}(n^2 \\cdot d)$.\n   - **Sequential computation:** $\\mathcal{O}(1)$: The entire attention matrix can be computed in parallel, and all comparisons can happen simultaneously.\n   - **Maximum path length:** $\\mathcal{O}(1)$: Since each token can directly connect to any other token via the attention mechanism, the maximum path length is just one step.\n\n2. **RNN**:\n\n   - **Per-layer complexity:** $\\mathcal{O}(n \\cdot d^2)$: The recurrent layer processes each token sequentially. The computation for each token involves combining the current token embedding (with $d$ dimensions) and the hidden state (also $d$-dimensional), resulting in an operational cost of $\\mathcal{O}(d^2)$. Since $n$ tokens are processed, the overall complexity is $\\mathcal{O}(n \\cdot d^2)$.\n   - **Sequential computation:** $\\mathcal{O}(n)$: Due to the sequential nature of RNNs, each token must wait for the computation of the previous token before processing the next.\n   - **Maximum path length:** $\\mathcal{O}(n)$: In an RNN, the path length between two tokens depends on the number of intermediate tokens between them.\n\n3. **CNN**:\n\n   - **Per-layer complexity:** $\\mathcal{O}(k \\cdot n \\cdot d^2)$: In the convolutional layer, a convolutional kernel of width $k$ slides over the entire sequence to compute local features. Each of the $n$ tokens requires computation on a $d$-dimensional embedding, and the cost of each convolution operation is proportional to $d^2$. Therefore, the total complexity is $\\mathcal{O}(k \\cdot n \\cdot d^2)$.\n   - **Sequential computation:** $\\mathcal{O}(1)$: Each convolution filter can be applied to the entire sequence simultaneously.\n   - **Maximum path length:** $\\mathcal{O}(\\log_k(n))$: Through stacking dilated convolution layers, the network can connect tokens that are farther apart in a logarithmic manner, with respect to $k$.\n\n4. **Restricted Self-Attention Layer**:\n\n   - **Per-layer complexity:** $\\mathcal{O}(r \\cdot n \\cdot d)$: In this case, each token can only attend to a neighborhood of size $r$. The attention matrix becomes $n \\times r$, but each matrix element still requires computation based on a $d$-dimensional embedding, so the overall complexity is $\\mathcal{O}(r \\cdot n \\cdot d)$.\n   - **Sequential computation:** $\\mathcal{O}(1)$: Similar to the unrestricted self-attention layer, all comparisons can be performed simultaneously.\n   - **Maximum path length:** $\\mathcal{O}(\\frac{n}{r})$: Since each token can only attend to a small neighborhood, the path length between two distant tokens increases to $\\mathcal{O}(\\frac{n}{r})$.\n\n### Experimental Results: Machine Translation\n\n\n\n![Machine Translation Results](/content/papers/assets/2b003147ddb8f1f6a0e22ce08f1806bd2216ebc4bd2baa6353356604c60ee87b.jpg)\n\n\n\nIn the WMT 2014 English-German translation task, the Transformer (big) improved the BLEU score by over 2.0 points compared to the previous best models (including ensemble models), setting a new record of 28.4 BLEU. This model trained for 3.5 days using 8 P100 GPUs. Even the base model surpassed all previously published models and ensemble models at a significantly lower training cost.\n\nIn the WMT 2014 English-French translation task, the Transformer (big) achieved 41.8 BLEU in Table 2 and the abstract, outperforming all previously published single models at less than a quarter of the previous best model's training cost. Section 6.1 instead says 41.0; the figure here follows the table and abstract.\n\n## Conclusion\n\nTransformer changed sequence modeling through training-time parallelism and shorter paths between distant tokens. Full attention has quadratic cost in sequence length, and inference efficiency still depends on decoding and implementation.\n\nIn the circles I encountered, its initial release attracted little attention outside technical audiences.\n\nAlthough Transformer was continuously and passionately discussed within the academic community for several years, it was widely known from natural language processing to computer vision fields. On the other hand, in the industrial sector, it was mostly engineers and researchers who took an interest in the topic.\n\n---\n\nHowever, when OpenAI's ChatGPT was released, everything changed.\n\nYes.\n\nEverything changed.\n","imageSizes":{"/content/papers/assets/29a55cb05497bdd9bbb3f3a96b7ed6656fda3552fa6a0fa5eb29e8e899c1acc1.jpg":{"width":756,"height":1080},"/content/papers/assets/cf4e6199fed125463d1bf049f3b141519f2057fbc55bc50bc1cc461d0021e48f.jpg":{"width":1024,"height":256},"/content/papers/assets/d01504d88522dd473549eae49a6d150720d98697ddc74a076bc69bb125647edd.jpg":{"width":1224,"height":668},"/content/papers/assets/05da9f1b22cfa674c685e532a517b699eac9d56ae0a208a6e32d16814de9353e.jpg":{"width":1224,"height":400},"/content/papers/assets/2b003147ddb8f1f6a0e22ce08f1806bd2216ebc4bd2baa6353356604c60ee87b.jpg":{"width":1224,"height":564}}}
