A long short-term memory (LSTM) network is a recurrent neural network (RNN) for sequential data. Where a network that treats inputs independently loses their order, an LSTM uses information from earlier time steps when processing the current one. This makes it useful for predicting the next token in text. section 8.0
Standard RNNs can struggle to learn relationships across long sequences because gradients diminish during training. LSTM units add a cell state that can carry relevant information along the sequence, helping retain longer-term patterns. LSTMs still struggle with extremely long-range dependencies and process tokens sequentially, unlike Transformers, which can train across sequence positions in parallel. section 8.1.2 section 1.3
To build a next-token text generator:
- Tokenize the training text and assign each distinct token an integer index. An LSTM cannot take raw text as input. section 8.1.3
- Cut the index sequence into inputs of 100 tokens. Shift each input one position to form its target sequence; batch the resulting pairs for training. section 8.1.3 section 8.3.2
- Pass indexes through a 128-dimensional word embedding, then a PyTorch LSTM layer and a linear layer sized to the vocabulary. The resulting logits can be converted to next-token probabilities. section 8.4
Learning a writing style
A model trained on Anna Karenina learns next-token patterns from the novel. For a small illustration of the training target, the input “how are you” pairs with “are you today”: each position asks the model to predict the following token. To generate text after training, start with a prompt, append a predicted token, and repeat. Temperature and top-K sampling can vary the output. section 8.1.3 section 8.3.2 section 8.5
Figure 8.2 An example of how an LSTM model is trained. We first break down the training text into tokens and assign a unique integer to each token, creating a numerical representation of the text as a sequence of indexes. We then divide this long sequence into shorter sequences of equal length. These sequences form the features (the x variable) of our model. We then generate the output y by shifting the input sequence one token to the right. This setup enables the LSTM model to predict the next token based on previous tokens in the sequence.
The diagram traces the preparation pipeline from tokens to integer-index inputs and one-token-shifted targets. section 8.1.3







