Juan Simancas

Artículo

Anatomy of a Transformer's Tensor

26 de octubre de 2026

Anatomy of a Transformer's Tensor

When you first study natural language processing, the journey usually begins with sequential models such as recurrent neural networks. These models read sentences word by word, updating a hidden state at step one, passing it to step two, and continuing until the end of the phrase. While intuitive, this step-by-step chain creates a computational bottleneck: a computer cannot work on the tenth word until it finishes processing the ninth.

To overcome this limitation the transformer takes a different path. Instead of reading tokens sequentially, it consumes an entire sequence of tokens at the same time. At the input stage, raw text is converted into numerical representations: words or sub-words are split into discrete tokens, mapped to numerical identifiers using a fixed vocabulary, and projected through an embedding table into continuous vectors. Because the model processes all tokens at once rather than one after another, it adds positional embeddings to these vectors so that word order is preserved. Finally several of these sequences are grouped into a batch to be processed together.

Once this preparation is complete, the input text lives inside your program as a single three-dimensional grid of numbers, denoted as:

X∈RB×T×CX \in \mathbb{R}^{B \times T \times C}

Every letter in this mathematical notation describes a concrete axis:

  • BB represents the batch size, meaning the number of separate sentences or documents you are feeding into the model at that moment.
  • TT represents the sequence length or time dimension, which is the number of token positions in each sentence.
  • CC represents the channel or embedding dimension, which is the size of the feature vector representing each token's meaning and position.

In the original paper Attention Is All You Need (Vaswani et al., 2017, arXiv:1706.03762), the authors formulated these dimensions algebraically. They denoted the embedding size CC as dmodeld_{model} (set to 512512 in their base architecture) and the sequence length TT as nn. The batch dimension BB was treated as an outer grouping for parallel computation.

Everything that happens next in the Transformer is an operation on this three-dimensional tensor. The goal of these operations is to allow the tokens to interact with each other. Before tokens can interact, however, each token must take on three distinct conversational roles:

  1. A Query (QQ), representing what the token is searching for in the rest of the sentence.
  2. A Key (KK), representing a label of what the token contains, which other queries can match against.
  3. A Value (VV), representing the actual information the token contributes if another token finds its key relevant.

To create these three roles the model applies a linear projection to XX. In a linear projection, every individual token vector of length CC is multiplied by a matrix of learned weights. This projection is position-wise: the model applies the exact same transformation matrix to every position across all sequences in the batch. Instead of multiplying XX three separate times by three different matrices to get QQ, KK, and VV, it is more straightforward to use a single wider matrix:

Wqkx∈RC×3CW_{qkx} \in \mathbb{R}^{C \times 3C}

Multiplying our input tensor X by this projection matrix yields a combined tensor:

QKV=XWqkv,QKV∈RB×T×3CQKV = X W_{\text{qkv}}, \qquad QKV \in \mathbb{R}^{B \times T \times 3C}

Observe what happened to the dimensions. The batch axis BB and the sequence length TT did not change; you still have the same number of sentences and the exact same number of token positions. Only the final axis grew: each position now holds 3C3C numbers instead of CC.

Because these 3C3C channels simply consist of queries, keys, and values placed side by side, we separate this final axis into three equal pieces of size CC:

Q,K,V∈RB×T×CQ, K, V \in \mathbb{R}^{B \times T \times C}

Now, each role has its own (B,T,C)(B, T, C) tensor.

At this point, you might wonder why we do not immediately calculate attention between all CC numbers of QQ and all CC numbers of KK. If we did that, each token would produce only a single similarity score with every other token. Language, however, carries multiple relationships at once. In the sentence "The cat sat on the mat because it was tired", the pronoun "it" needs to connect to "cat" to resolve reference, but it also needs to connect to "was tired" to resolve the predicate.

To allow the model to track several relationships at the same time, the Transformer divides the channel axis into HH separate groups called attention heads. If each head receives DD channels, the total number of channels must satisfy a simple arithmetic constraint:

C=H⋅D  ⟹  D=CHC = H \cdot D \implies D = \frac{C}{H}

In Vaswani et al. (2017), the number of heads HH was designated as hh (set to 88), and the dimension per head DD was designated as dkd_k (set to dk=512/8=64d_k = 512 / 8 = 64).

This divisibility equation is strict. If your embedding size is C=12C = 12 and you choose H=3H = 3 heads, each head receives D=4D = 4 feature dimensions. But if you have C=10C = 10 and attempt to divide it across H=3H = 3 heads, you cannot divide 1010 numbers into 33 equal integer pieces. The computer cannot allocate fractional numbers to a head, so the architecture cannot function without changing CC or HH.

When CC is divisible by HH, we reshape the final dimension of each tensor from CC into (H,D)(H, D):

(B,T,C)⟶(B,T,H,D)(B, T, C) \longrightarrow (B, T, H, D)

This reshape does not change any values or create new data. It simply places conceptual boundaries along the channel axis, indicating that the first DD numbers belong to Head 1, the next DD numbers belong to Head 2, and so forth.

However, the tensor is now in the shape (B,T,H,D)(B, T, H, D). If you read this shape aloud, it says: for each sentence in the batch (BB), go to each word position (TT), and examine its heads (HH).

This ordering presents a problem for attention. Self-attention does not compare different heads belonging to the same word. Instead, it compares all words in the sentence within the same head. To compute Head 1, we need all TT words laid out together under Head 1.

To achieve this alignment, the model swaps the second and third axes:

(B,T,H,D)→transpose(1,2)(B,H,T,D)(B, T, H, D) \xrightarrow{\text{transpose}(1, 2)} (B, H, T, D)

Reading this new shape reveals the logic of the transformation: for each sentence (BB), go to each head (HH), and look at the sequence of words (TT), where each word is described by its head vector of size DD.

With the tensor arranged as (B,H,T,D)(B, H, T, D), calculating attention becomes direct. For any given head in any sentence, our queries form a matrix of shape (T,D)(T, D) and our keys form a matrix of shape (T,D)(T, D). Multiplying queries by transposed keys matches words against words:

(T,D)×(D,T)⟶(T,T)(T, D) \times (D, T) \longrightarrow (T, T)

The result is a T×TT \times T grid for each head, containing the pairwise connection strength between every token position ii and every token position jj.

The entire journey of the representation through these transformations forms a continuous geometric pipeline:

X∈RB×T×C→projectionQKV∈RB×T×3C→splitQ,K,V∈RB×T×C→view(B,T,H,D)→transpose(B,H,T,D)X \in \mathbb{R}^{B \times T \times C} \xrightarrow{\text{projection}} QKV \in \mathbb{R}^{B \times T \times 3C} \xrightarrow{\text{split}} Q, K, V \in \mathbb{R}^{B \times T \times C} \xrightarrow{\text{view}} (B, T, H, D) \xrightarrow{\text{transpose}} (B, H, T, D)

Every step in this sequence maintains a clear physical meaning. The input grid of token embeddings is expanded to generate distinct conversational roles, divided into smaller subspaces to capture multiple semantic relationships in parallel, and reordered so that tokens can evaluate each other across the entire sentence.