Why AI Surprises Perché l'AI sorprende

How the Transformer Really Works Come funziona davvero il transformer

Mirko Bradley — mirkobradley.com

Imagine you have a text written in a language you do not know. You cannot understand the words, but you can observe which words appear close to each other, which ones repeat together, and which ones occupy similar positions in sentences. From those observations you can build a map of the relationships between the symbols, even without knowing what they mean. The transformer does something structurally similar, on a vastly larger scale and with precise mathematical tools.

Immaginate di avere davanti un testo scritto in una lingua che non conoscete. Non capite le parole, ma potete osservare quali parole appaiono vicine, quali si ripetono insieme e quali occupano posizioni simili nelle frasi. Da quelle osservazioni riuscite a costruire una mappa delle relazioni tra i simboli, anche senza sapere cosa significano. Il transformer fa qualcosa di strutturalmente analogo, su scala enormemente maggiore e con strumenti matematici precisi.

When we say that an AI model "reads" a text, we are using a metaphor. The model does not read in the way a human being does. It performs mathematical operations on numbers. Understanding which operations it performs, and why they produce what they produce, is the starting point of this series.

Quando si dice che un modello di intelligenza artificiale "legge" un testo, si usa una metafora. Il modello non legge nel senso in cui lo fa un essere umano, esegue operazioni matematiche su numeri. Capire quali operazioni, e perché producono quello che producono, è il punto di partenza di questa serie.

The first step is turning words into numbers. Every word, or more precisely every fragment of text the model treats as a basic unit, is converted into a vector, that is, a list of numbers, typically between 768 and 12,288 values. This vector is not arbitrary. It is learned during training so that words with similar meanings end up close to each other in mathematical space. "King" and "queen" are closer to each other than "king" and "table," because those words appear in similar contexts in the text the model was trained on, and the training process encoded that proximity in geometric form.

Il primo passaggio è la trasformazione delle parole in numeri. Ogni parola, o più precisamente ogni frammento di testo che il modello usa come unità di base, viene convertita in un vettore, cioè in una lista di numeri, tipicamente tra 768 e 12.288 valori. Questo vettore non è arbitrario, ma viene appreso durante l'addestramento in modo che parole con significati simili si trovino vicine nello spazio matematico. "Re" e "regina" sono più vicini tra loro che "re" e "tavolo", perché quelle parole appaiono in contesti simili nel testo su cui il modello è stato addestrato e il processo di addestramento ha codificato quella prossimità in forma geometrica.

The second step is the central mechanism of the transformer: attention. To understand it, consider a sentence: "The bank refused the loan because it was in difficulty." Who was in difficulty, the bank or the applicant? To answer, one must understand the relationships between the words. The attention mechanism does exactly this: for each word in the sentence, it calculates how relevant every other word is for interpreting it correctly. The word "it" looks at all the other words in the sentence and decides which one to connect to, based on the entire context.

Il secondo passaggio è il meccanismo centrale del transformer: l'attenzione. Per capirlo, immaginiamo una frase: "La banca ha rifiutato il prestito perché era in difficoltà." Chi era in difficoltà, la banca o il richiedente? Per rispondere, bisogna capire le relazioni tra le parole. Il meccanismo di attenzione fa esattamente questo: per ogni parola della frase, calcola quanto ogni altra parola è rilevante per interpretarla correttamente. La parola "era" guarda tutte le altre parole della frase e decide a quale agganciarsi, in funzione del contesto intero.

This calculation happens through three projections of the same starting vector: a query (what this word is looking for), a key (what every other word offers), and a value (what every other word transmits if selected). The dot product between query and key measures relevance. The softmax function turns those scores into weights that sum to one. The final result is a weighted average of the values, in which the most relevant words carry more weight. The equation is:

Questo calcolo avviene attraverso tre proiezioni dello stesso vettore di partenza: una query (cosa sta cercando questa parola), una key (cosa offre ogni altra parola) e un value (cosa trasmette ogni altra parola se viene selezionata). Il prodotto scalare tra query e key misura la rilevanza. La funzione softmax converte quei punteggi in pesi che sommano a uno. Il risultato finale è una media pesata dei valori, in cui le parole più rilevanti pesano di più. L'equazione è:

Attention(Q, K, V) = softmax(QKT / √dk) V.
Attention(Q, K, V) = softmax(QKT / √dk) V.

This is the only equation in this series. It is worth reading it slowly. Q, K, and V are the three projections described above. The product QKT measures the relevance between every pair of words. The factor √dk stabilizes the calculations as dimensions grow. Softmax turns the scores into weights. The final product with V produces the result: a new representation of each word, enriched by the context.

Questa è l'unica equazione di questa serie. Vale la pena leggerla con calma. Q, K e V sono le tre proiezioni descritte sopra. Il prodotto QKT misura la rilevanza tra ogni coppia di parole. Il fattore √dk serve a stabilizzare i calcoli al crescere delle dimensioni. Softmax trasforma i punteggi in pesi. Il prodotto finale per V produce il risultato: una nuova rappresentazione di ogni parola, arricchita dal contesto.

The transformer applies this mechanism multiple times in parallel, each time with different parameters: each attention "head" looks at the sequence from a different perspective. One might capture grammatical relations, another semantic relations, another long-distance references. The results are combined.

Il transformer applica questo meccanismo più volte in parallelo, con parametri diversi ogni volta: ogni "testa" di attenzione guarda la sequenza da una prospettiva diversa. Una potrebbe catturare relazioni grammaticali, un'altra relazioni semantiche, un'altra ancora riferimenti a distanza. I risultati vengono combinati.

On top of this comes the residual stream: a vector that runs through the entire network from beginning to end, accumulating contributions from every layer without erasing them. It is not a technical detail. It is what allows the model to build increasingly rich representations as the text moves through the layers. Each layer reads from the residual stream, adds something, and writes it back. The final result emerges from the accumulation of all these contributions.

A tutto questo si aggiunge il residual stream: un vettore che attraversa l'intera rete dall'inizio alla fine, accumulando contributi da ogni layer senza cancellarli. Non è un dettaglio tecnico, è ciò che permette al modello di costruire rappresentazioni sempre più ricche mentre il testo avanza attraverso i layer. Ogni layer legge dal residual stream, aggiunge qualcosa e lo riscrive. Il risultato finale emerge dall'accumulo di tutti questi contributi.

What we have described is a system of linear mathematical operations, with some non-linearities (the softmax, the activation functions in the feed-forward layers). Nothing more. Yet from this system emerge structures that no one designed: multi-step reasoning, emotional representations, metacognitive abilities. How is that possible? That is the question this series sets out to answer, one essay at a time.

Quello che abbiamo descritto è un sistema di operazioni matematiche lineari, con alcune non linearità (la softmax, le funzioni di attivazione nei layer feed-forward). Niente di più. Eppure, da questo sistema emergono strutture che nessuno ha progettato: ragionamenti in più passi, rappresentazioni emotive, capacità metacognitive. Come è possibile? È la domanda cui questa serie si propone di rispondere, un essay alla volta.

Human Text Is Not Neutral Data → Il testo umano non è dati neutri →