Transformers Generate One Word at a Time
Transformers can chat, answer questions, follow commands, write stories and poems, even write code. It is easy to imagine them planning a whole response and then writing it out. They do nothing of the sort. A transformer generates text one word at a time. Ask hello, how are you, and it does not produce an answer. It produces the next word, perhaps doing. Then it feeds the longer sentence back in and produces the next word again. Ask it to write a story and it picks once, then upon, then a, then time, and keeps going until a story exists.
That sounds too simple to work, and for a long time it did not work well. The obvious way to guess the next word is to count. Look at every time are appears in a dataset and pick the most common next word, happy. That is a one-gram. Use the last three words, hello how are, and pick the most common next word, things. That is a three-gram. Use the last ten words and the guess gets better, but the exact ten-word sentence may have appeared only twice, both times followed by the. Longer context means a smarter guess and a rarer match. Sentences like the other day I was walking and five unicorns said may never have appeared at all.
Neural networks were the next step: feed in the sentence and let the network guess. Phone keyboards do this, and if you keep tapping the middle suggestion you get a sentence that sounds fine in three-word bursts but falls apart as a whole, drifting from greetings to well-wishes with no thread connecting them. Every three or four words make sense, but the whole thing does not. The network remembers a few words at a time. It can build short phrases, not long text. To build long text you need a transformer.
The architecture is a pipeline. Tokenization splits the text into tokens. Embedding turns each token into numbers, using ideas like word2vec, where similar words get similar numbers. Positional encoding adds order, because the model has no built-in sense of sequence. Then come the transformer blocks, the main engine: attention lets the tokens look at each other, and a feed-forward neural network does the heavy lifting. Stack many blocks, and finish with a softmax that turns the final numbers into a probability for every possible next word. One word out, feed it back in, repeat. That loop is the whole trick.
Everything else in these models exists to make that one-word guess as good as possible. Attention, embeddings, the stack of blocks: all of it serves the next word.
Try this
bashpip install transformers python -c "import transformers; print(transformers.__version__)"
Sources
- Source: What are Transformer Models and how do they work? - Luis Serrano Academy
