If we want to really understand how today’s Large Language Models (LLMs) like GPT or Hugging Face models work, we are not start directly with transformers and attention mechanism. It’s better to first learn the basic ideas that came before them like Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM).
That’s why I decided to build a text summarizer from scratch using an LSTM-based encoder-decoder model (without using pretrained models).
In this article, I’ll talk about :-
- Why I started with LSTMs instead of transformers
- How I built the model step by step
- The challenges I faced while training it
- The key lessons I learned before moving toward attention and transformers
1. Why I started with LSTM instead of transformers :
Before diving into let’s first understand → why ?
RNN to LSTM to Transformers: RNNs were the first models for sequences, but they struggled with long-term dependencies. LSTMs improved on this with memory cells to remember important information over longer sequences. Transformers then solved some remaining limitations using attention mechanism so the
Regular RNNs were the first models for handling sequences but they have big weakness they quickly forget information when the input sequence was long this happened because of the vanishing gradient problem during training the gradients used to update weights became smaller and smaller as they were backpropagated through many time steps so the model not learn long-term dependencies.
Regular RNNs process sequences step by step: RNN hidden state update equation
ht = tanh( Wh.ht − 1 + Wxt + b )
- Wh.ht−1 is transforms the previous hidden state
- Wx.Xt is transforms the current input
- b is bias term for flexibility
Why tanh bcz It’s values between -1 and 1, which helps keep the hidden states stable and prevents them from growing too large.
process sequences x1 , x2 , . . . . , xT one step at a time At each timestep t , it keeps a hidden state ht that summarizes all information seen so far
But Gradients vanish or explode over long sequences Consequence: Early words in a sentence are “forgotten” by the time the network reaches the end.
Example: In the sentence I grew up in India and last year I moved to… a simple RNN might completely forget India by the time it reaches the end so it can not connect the move to the right city.
So LSTMs fix this by introducing gates and a memory cell:
Forget gate decides what information to throw away and Input gate decides what new information to store also Cell state acts like a conveyor belt, carrying information forward almost unchanged, so important context can survive across many steps.
Because of this LSTM :
Remember long-range context like connecting India from the start of the sentence to moved to much later and Control what to remember and what to forget, instead of just letting information fade away and Train more reliably without gradients disappearing as quickly.
LSTM as the foundation: They are great at handling sequences and learning dependencies in text, which is exactly what we need for tasks like summarization.

At time step t, given input xt, previous hidden state ht−1 and previous cell state Ct−1.
At each timestep t, the LSTM has:
Input xt means current word / feature and Previous hidden state ht−1 which is short-term memory and Previous cell state Ct−1 which is long-term memory , It computes four things
Forget Gate — decides what information to throw away
ft = σ ( Wf ⋅ [ ht − 1 , xt ] + bf )
ft: Think of it as a filter It looks at the new input + old hidden state and decides what parts of the old memory (Ct−1) to keep or drop.
Example : In I live in India later words might make India important to keep, or not
Input Gate — decides what new information to store :
it = σ ( Wi ⋅ [ ht − 1 , xt ] + bi )
Candidate Cell State — creates new candidate values :
Ct = tanh ( WC ⋅ [ ht − 1 , xt ] + bC )
Input Gate it & Candidate Ct: Together, they decide what new info to add to memory If the sentence is like
Example : I moved to America then the gate lets America into the memory
Update Cell State — combine old state partly forgotten with new candidate partly added
Ct = ft ⊙ Ct − 1 + it ⊙ Ct
Cell State Ct : This is the LSTM long-term memory It’s updated gradually by forgetting some old info and adding new info.
Output Gate — decides what part of the cell state to output
ot = σ ( Wo ⋅ [ ht − 1 , xt ] + bo )
Output Gate ot : Decides what part of the memory to expose as the hidden state ht used by the next layer or for predictions
New Hidden State — output for this step
ht = ot ⊙ tanh ( Ct )
⊙ :- element-wise multiplication
By combining these gates, LSTMs can remember information over long sequences while also updating dynamically when new info appears. That’s why LSTMs solved the vanishing gradient problem that killed simple RNNs they have explicit control over what to remember, forget, and output so
So I have drawn an example to show how an LSTM works we are already seen all the gates and their functions, and now we are visualize how the internal process actually works.



2. How I built the model step by step :
Data Preprocessing →
- Lowercasing the text : Text like “Hello” and “hello” are treated as different tokens by LSTMs, which increases vocabulary and can confuse the model. Converting all text to lowercase reduces vocabulary size and helps the model generalize better.
new_data['dialogue'] = new_data['dialogue'].str.lower()
new_data['summary'] = new_data['summary'].str.lower()
- Cleaning symbols and extra spaces : → Non-letter and number , characters are rarely useful and can confuse the model, especially with a limited vocabulary so we keep only letters, numbers, and spaces.
Example: converts “Hello !! How Are You ?” and Ans is “hello how are you”
and after that we are Removes extra spaces at the beginning and end. so that it Keeps the text neat for tokenization.
import re
def clean_text(text):
text = text.lower() # lowercase the letter
text = re.sub(r'[^a-zA-Z0-9\s]', '', text) # then remove symbols and punctuations
text = re.sub(r'\s+', ' ', text) # and also remove extra spaces
return text.strip()
3. Applying the cleaning function to both columns : If the summary contains messy symbols or different casing than the dialogue, the model may struggle to learn correct mappings.
# then cleaning the entier dataset :-
new_data['dialogue'] = new_data['dialogue'].apply(clean_text)
new_data['summary'] = new_data['summary'].apply(clean_text)
Text Tokenization
After cleaning the text, Tokenization Converts each word into a unique number (token) so the model can understand text, creating a mapping between words and numbers.
Example : The cat sat on the mat → [ 12 , 45 , 78 , 5 , 12 , 99 ]
This mapping allows the LSTM model to process sequences of numbers instead of raw text ok now for that
- Adding <sos> and <eos> tokens :
- <sos> = Start of Sequence → tells the model where to begin generating the summary.
- <eos> = End of Sequence → tells the model when to stop generating.
This is the very very important and main part of sequence-to-sequence models so the decoder determines exactly when to start and stop.
new_data['summary'] = new_data['summary'].apply(lambda x: '<sos> ' + x.strip() + ' <eos>')
2. Building the vocabulary :
like this way new_data[‘dialogue’] + new_data[‘Summary’]
- We combine all dialogues and summaries to make a single vocabulary.
- Tokenizer converts each unique word into a unique integer.
- <unk> handles unknown words not seen during training.
building_vocab = new_data['dialogue'].tolist() + new_data['summary'].tolist()
tokenizer = Tokenizer(lower=True, filters='', oov_token='<unk>') # ==> num_words=3000
tokenizer.fit_on_texts(building_vocab)
and after that Convert sentences to sequences and LSTM can process numbers instead of raw text.
Example Output : —
dialogue_sequences = tokenizer.texts_to_sequences(new_data['dialogue'])
summary_sequences = tokenizer.texts_to_sequences(new_data['summary'])
print("Sample Summary:", new_data['summary'].iloc[0])
print("Tokenized:", summary_sequences[0])
# Output :-
Sample Summary: <sos> amanda baked cookies and will bring jerry some tomorrow <eos>
Tokenized: [12, 400, 3634, 1568, 7, 14, 207, 634, 49, 99, 13]
Padding Sequences
Now After tokenization, sentences become number sequences of different lengths. LSTMs require all sequences in a batch to have the same length to process them efficiently, so shorter sequences are padded.
Now What Padding Does :- (padding = ‘post’ ) adds zeros at the end of the sequence.
Example :- This ensures all sentences in the batch are the same length. Original [ 1 , 2, 3 ] : Padded [ 1 , 2, 3, 0 , 0 , 0]
- LSTMs process sequences step by step, and each batch must have uniform length.
- Padding allows the model to ignore extra zeros (if mask_zero = True in Embedding layer) tells the model to ignore padding tokens (0), very important in NLP.
- Helps in efficient training on batches without losing information. what is Embedding layer we see next
padded_dia = pad_sequences(dialogue_sequences, padding='post')
padded_sum = pad_sequences(summary_sequences, padding='post') # This is the Decoder Input
Splitting Summaries into Input & Target for Decoder
In a Seq2Seq (Encoder-Decoder) model, the decoder doesn’t just see the entire summary at once.
- Decoder Input : what the model receives at each step to predict the next word.
- Decoder Target : the actual word the model should predict at that step.
At time step 1, the decoder sees <sos> and should predict hello. At time step 2, it sees hello and should predict how , and so on… This shifting ensures the model learns to generate the sequence word by word.
padded_sum = np.array(padded_sum)
decoder_input = padded_sum[:, :-1] # Remove last token for decoder input bcz it is <SOS>
decoder_target = padded_sum[:, 1:] # Remove first token for decoder target bcz it is <EOS>
Encoder–Decoder Summarization Model (Embedding + LSTM)
We start with a basic Seq2Seq using LSTM and Embedding layers, and later in Part 2, we are trying to explained it with Self-Attention to make it more powerful.
Embedding Layer ??
Now what is Embedding Layer right so basically it converts each word / token into a dense vector of numbers that captures its meaning and relationships with other words. Instead of representing words as sparse one-hot vectors example : ‘king’ and ‘queen’ will have vectors that are closer in the embedding space than ‘king’ and ‘apple’.

1. LSTM Encoder :
The encoder processes the input sequence one word at a time, converting each word into a hidden state that captures both its meaning and its relation to previous words. These hidden states are gradually updated as the sequence progresses, and the final hidden state (along with the cell state, in LSTM) serves as a compact context vector that summarizes the entire input sequence.
Now embedding converts integer tokens into dense vectors that capture semantic meaning

from tensorflow.keras.layers import Input, Embedding, LSTM, Dense
from tensorflow.keras.models import Model
encoder_inputs = Input(shape=(padded_dia.shape[1],), name="encoder_input")
enc_emb = Embedding(input_dim=vocab_size, output_dim=embedding_dim, mask_zero=True)(encoder_inputs)
encoder_outputs, state_h, state_c = LSTM(latent_dim, return_state=True)(enc_emb)
LSTM ( latent_dim , return_state = True ) : outputs
State_h : hidden state
state_c : cell state
2. LSTM Decoder :
The decoder generates the summary one word at a time, using the context vector from the encoder as a starting point
The decoder generates the summary one word at a time, using the context vector from the encoder as a starting point. At each step, it predicts the next word based on the previous word and its hidden states. During training, teacher forcing helps guide the decoder with the actual target words, while during inference, it must rely on its own predictions until an end token is generated.

decoder_inputs = Input(shape=(decoder_input.shape[1],), name="decoder_input")
dec_emb = Embedding(input_dim=vocab_size, output_dim=embedding_dim, mask_zero=True)(decoder_inputs)
decoder_lstm = LSTM(latent_dim, return_sequences=True,dropout=0.3,return_state=True)
decoder_outputs, _, _ = decoder_lstm(dec_emb, initial_state=[state_h, state_c])
So the decoder_inputs sequence for the decoder (from previous step <sos> + words) then Embedding converts tokens into vectors and LSTM generates outputs for each time step Initial_state = [ State_h , state_c ] : feeds encoder’s context into the decoder so it “knows” the input sequence , and return_sequences outputs a sequence of hidden states (needed for predicting each word).
So Basically What i am trying to say :
The encoder compresses the input dialogue into a context vector and then decoder generates the summary word by word using that context.
Embedding layers help convert tokens into dense vectors so the LSTM can process semantic information. So This model is from scratch at the architecture level no pretrained summarizers are used.
Output Layer :
decoder_dense = Dense(vocab_size, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
Now Final Step is Defining, Compiling, and Training the Model
After building the encoder and decoder layers, the next step is to connect them, compile the model, and train it on our data.
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
Inputs:
encoder_inputs : the dialogue sequences
decoder_inputs : the summary sequences (shifted with <SOS> token)
Output:
decoder_outputs : the predicted sequence of word tokens
Compiling the Model
so we are used Optimizer (RMSprop) it updates model weights during training efficiently for LSTM networks and Loss are used is sparse_categorical_crossentropy because it calculates the difference between predicted words and actual words so We use sparse because the targets are integers, not one-hot vectors and Metrics (accuracy) to track how well the model predicts the next word during training This step sets up how the model learns from the data.
Now i have completes the first version of my text summarizer and model now learns to map input dialogues to summaries word by word.
model = Model(
[encoder_inputs, decoder_inputs],
decoder_outputs)
model.compile(
optimizer='RMSprop',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)

3 . The challenges I faced while training it
One of the first problems I faced was that LSTMs still forget things when the text is too long. They are better than simple RNNs, but after many steps they lose track of what came earlier.
Another issue was training speed. LSTMs read one word at a time, so when the dataset is big or the dialogues are long, training becomes really slow. On the other hand, transformers can look at the whole sequence at once with self-attention, which makes them much faster to train.
I also ran into something called exposure bias. During training, the decoder always gets the correct previous word as input, but during testing it has to use its own predictions. If it predicts one wrong word, that mistake is used again in the next step, and the errors keep adding up quickly.
4. The key lessons I learned before moving toward attention and transformers
I learned a lot from building this LSTM summarizer. I found that while LSTMs are good for learning how sequence-to-sequence models work, they struggle with long texts, train slowly, and often make mistakes during inference.
I also noticed that simple things like cleaning the data and choosing the right vocabulary make a big difference <unk> tokens and messy text can easily ruin the results.
Most importantly, working with LSTMs showed me the exact problems that attention and transformers are built to solve, like remembering context better, handling rare words, and training faster. In short, LSTMs gave me the basic foundation I needed before moving on to attention and modern models. I noticed that LSTM still forgets after 30+ words, which showed me why attention mechanisms exist. Adding <sos> and <eos> tokens was critical without it, the decoder didn’t know where to start or stop.
In Part 2 we will see how the Attention mechanism overcomes the problems we faced in this project while building a text summarization model.