# Transformer

* Transformer is a Seq2Seq model.
* Transformer is not RNN.
* Purely based attention and dense layers.
* Higher accuracy than RNNs on large datasets.

## From Single-Head to Multi-Head

* Single-head self-attention can be combined to form a multi-head self-attention.
* Single-head attention can be combined to form a multi-head attention.
* Using $$l$$ single-head self-attentions (which do not share parameters.)
  * A single-head self-attention has 3 parameter matrices: $$W\_Q, W\_K, W\_V$$
  * Totally $$3l$$ parameters matrices.
* Concatenating outputs of single-head self-attentions.
  * Suppose single-head self-attentions' outputs are $$d \times m$$ matrices.

    • Multi-head’s output shape: $$(ld) \times m$$

![](/files/qbXUmpTHpjVrXbnBM17e)

## Self-Attention Layer + Dense Layer

![](/files/F5A60AWt2QAPBU2NojvF)

## Stacked Self-Attention Layers

![](/files/kld5zewjiv4YuVgwC9IL)

## Transformer's Encoder

![](/files/jrMLhrY8gLpMV2eookg1)

* Transformer is a Seq2Seq model (encoder + decoder).
* Encoder’s inputs are vectors $$x\_1,x\_2,...,x\_m$$.
* Decoder’s inputs are vectors $$x'\_1,x'\_2,...,x'\_t$$.
* Transformer’s encoder contains 6 stacked blocks.
* 1 block ≈ 1 multi-head self-attention layer + 1 dense layer.
  * Input shape: $$512 \times m$$
  * Output shape: $$512 \times m$$
* Encoder network is a stack of 6 such blocks

## Transformer’s Decoder : One Block

![](/files/miZRJZ1X6LRPjlJyJXWT)

![](/files/8mAOPfbPEe1hW7oH0Nuc)

* 1 decoder block $$\approx$$multi-head self-attention + multi-head attention + dense
  * Input shape: $$(512 \times m, 512 \times t)$$
  * Output shape: $$512 \times t$$
* Decoder network is a stack of 6 such blocks

## Put things together: Transformer

![](/files/McGvmCQuSE7fbFuPaiHg)

* Transformer is Seq2Seq model; it has an encoder and a decoder.
* Transformer model is not RNN.
* Transformer is based on attention and self-attention.
* Transformer outperforms all the state-of-the-art RNN models.

## Reference

[youtube](https://www.youtube.com/watch?v=aJRsr39F4dI\&t=2s)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ztlevi.gitbook.io/ml-101/nlp/transformer.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
